SpringBoot+Redis缓存简单配置

老吴2018-08-15 10:11后端12338浏览


版权声明:本篇文章为原创文章,转载请注明出处。https://yao2san.com/article/1089

SpringBoot+Redis缓存简单配置

依赖:

<!--redis-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

application.properties:

//可以不用配置,有默认配置
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=1
spring.redis.timeout=100

Redis配置类:

@Configuration
public class RedisConfig {
    /*缓存管理器配置*/
    @Bean
    public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        //设置缓存过期时间
        //FIXME 修改下边的缓存过期时间
        cacheManager.setDefaultExpiration(60*60);
        return cacheManager;
    }
    /*设置RedisTemplate*/
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory){
        StringRedisTemplate template = new StringRedisTemplate(factory);
        setSerializer(template);//设置序列化工具
        template.afterPropertiesSet();
        return template;
    }
    /*设置序列化工具*/
    private void setSerializer(StringRedisTemplate template){
        @SuppressWarnings({ "rawtypes", "unchecked" })
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
    }
}

Application启动类:

加上注解@EnableCaching开启缓存支持

使用缓存

常用的注解有:

@Cacheable

@CachePut

@CacheEvict

作用不在详述,简单总结如下:

@Cacheable:有缓存取缓存,没有则放入缓存

@CachePut:有缓存刷新缓存,没有则放入

@CacheEvict:有缓存则清除,可以指定在方法执行前还是执行后清除

赞一个! (36)

文章评论(如需发表图片,请转至留言)