Spring 的缓存抽象对缓存功能提供了声明式的支持,缓存管理器(cache manager)是缓存抽象的核心,它能够与多个缓存实现进行集成; Spring 缓存原理是创建一个切面(aspect)并触发 Spring 缓存注解的切点(pointcut),根据所使用的注解和缓存的状态,这个切面会从缓存中获取数据,将数据添加到缓存或从缓存中移出数据。
添加 redis 缓存依赖 1 2 3 4 <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-data-redis</artifactId > </dependency >
Spring Data Redis 提供了 RedisCacheManager 作为缓存管理器的实现,并通过 RedisTemplate 将缓存条目存储到 redis 服务中。
application.yml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 spring: redis: database: 0 host: 127.0 .0 .1 port: 6379 password: jedis: pool: min-idle: 0 max-idle: 8 max-active: 8 max-wait: -1ms server: port: 8080
缓存配置类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import org.springframework.cache.annotation.EnableCaching;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration @EnableCaching public class CacheConfig { @Bean public RedisTemplate redisTemplate (RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class )) ; redisTemplate.afterPropertiesSet(); return redisTemplate; } }