Redis系列三 - Spring boot如何使用redis做缓存及缓存注解的用法总结

本文详述了Spring Boot如何集成Redis作为缓存,并配置RedisCacheManager。介绍了@Cacheable、@CacheEvict、@CachePut和@CacheConfig等缓存注解的使用,包括其属性和注意事项,以及测试方法。
摘要由CSDN通过智能技术生成

1. 概述

本文介绍Spring boot 如何使用redis做缓存,如何对redis缓存进行定制化配置(如key的有效期)以及spring boot 如何初始化redis做缓存。使用具体的代码介绍了@Cacheable,@CacheEvict,@CachePut,@CacheConfig等注解及其属性的用法。

2. spring boot集成redis

2.1. application.properties

配置application.properties,包含如下信息:

  • 指定缓存的类型
  • 配置redis的服务器信息
  • 请不要配置spring.cache.cache-names值,原因后面再说
## 缓存
# spring.cache.cache-names=book1,book2
spring.cache.type=REDIS

# REDIS (RedisProperties)  
spring.redis.database=0
spring.redis.host=192.168.188.7
spring.redis.password=
spring.redis.port=6379
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0  
spring.redis.pool.max-active=100 
spring.redis.pool.max-wait=-1

2.2. 配置启动类

  • @EnableCaching: 启动缓存
  • 重新配置RedisCacheManager,使用新的配置的值
@SpringBootApplication
@EnableCaching // 启动缓存
public class CacheApplication {
   
    private static final Logger log = LoggerFactory.getLogger(CacheApplication.class);

    public static void main(String[] args) {
        log.info("Start CacheApplication.. ");
        SpringApplication.run(CacheApplication.class, args);

    }

    /**
     * 重新配置RedisCacheManager
     * @param rd
     */
    @Autowired
    public void configRedisCacheManger(RedisCacheManager rd){
        rd.setDefaultExpiration(100L);
    }
}

经过以上配置后,redis缓存管理对象已经生成。下面简单介绍spring boot如何初始化redis缓存。

2.3. spring boot 如何初始化redis做缓存

缓存管理接口org.springframework.cache.CacheManager,spring boot就是通过此类实现缓存的管理。redis对应此接口的实现类是org.springframework.data.redis.cache.RedisCacheManager。下面介绍此类如何生成。

首先我们配置application.properties的spring.redis.* 属性后@EnableCaching后,spring会执行RedisAutoConfiguration,初始化RedisTemplate和StringRedisTemplate

@Configuration
@ConditionalOnClass({ JedisConnection.class, RedisOperations.class, Jedis.class })
@EnableConfigurationProperties(RedisProperties.class)
public class RedisAutoConfiguration {
   
/**
 * Standard Redis configuration.
 */
@Configuration
protected static class RedisConfiguration {
   
    ….
    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(
        RedisConnectionFactory redisConnectionFactory)
         
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值