zoukankan      html  css  js  c++  java
  • SpringBoot+Redis缓存简单配置

    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:有缓存则清除,可以指定在方法执行前还是执行后清除

  • 相关阅读:
    Spring spEL
    Spring 使用外部部署文件
    Spring 自动装配
    spring 属性配置细节
    hdu 1054 Strategic Game
    fzu 2037 Maximum Value Problem
    将博客搬至CSDN
    HDU 4714 Tree2Cycle
    HDU 1009 The Shortest Path in Nya Graph
    POJ 1942 Paths on a Grid 组合数的优化
  • 原文地址:https://www.cnblogs.com/cnsec/p/13286668.html
Copyright © 2011-2022 走看看