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

  • 相关阅读:
    华强北三代悦虎1562A怎么样?
    改丝印的假华强北三代1562A,用芯良苦!
    华强北三代过软件检测的佳和1562A
    Unlua静态导出
    Unlua编程基础
    Android JNI调用
    手机屏幕参数
    UE4 stats性能埋点
    【JWT】JSON Web Token
    【算法】一致性哈希算法实现
  • 原文地址:https://www.cnblogs.com/cnsec/p/13286668.html
Copyright © 2020-2023  润新知