美文网首页
spring boot 2.1.2.RELEASE整合cache

spring boot 2.1.2.RELEASE整合cache

作者: Jabwin | 来源:发表于2019-06-29 09:36 被阅读0次

    针对spring boot 2.1.2.RELEASE,其中问题尚需改动。
    pom.xml

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-cache</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-pool2</artifactId>
            </dependency>
    

    application.properties(哨兵模式)

    #Matser的ip地址
    spring.redis.host=192.168.1.100
    #端口号
    spring.redis.port=6379
    spring.cache.redis.time-to-live=1800
    spring.redis.database=1
    spring.redis.sentinel.master=mymaster
    spring.redis.sentinel.nodes=192.168.1.101:6379
    spring.redis.lettuce.pool.max-active=8
    spring.redis.lettuce.pool.max-idle=8
    spring.redis.lettuce.pool.max-wait=-1ms
    spring.redis.lettuce.pool.min-idle=0
    spring.redis.timeout=2000
    

    RedisConfig.java

    
    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.annotation.PropertyAccessor;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializationFeature;
    import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.cache.Cache;
    import org.springframework.cache.annotation.CachingConfigurerSupport;
    import org.springframework.cache.annotation.EnableCaching;
    import org.springframework.cache.interceptor.CacheErrorHandler;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.cache.RedisCacheConfiguration;
    import org.springframework.data.redis.cache.RedisCacheManager;
    import org.springframework.data.redis.cache.RedisCacheWriter;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.RedisSerializationContext;
    import java.time.Duration;
    /*************************************************************
     * cache配置
     * @author Jabwin
     * @since 2019-06-09
     *************************************************************
     */
    @Configuration
    @EnableCaching
    @Slf4j
    public class RedisConfig extends CachingConfigurerSupport
    {
        @Value("${spring.cache.redis.time-to-live}")
        private Long redisKeyTtl;
    
        /** 异常处理 */
        @Override
        public CacheErrorHandler errorHandler()
        {
            CacheErrorHandler cacheErrorHandler = new CacheErrorHandler()
            {
                @Override public void handleCacheGetError(RuntimeException exception, Cache cache, Object key)
                {
                    RedisErrorException(exception, key);
                }
                @Override public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value)
                {
                    RedisErrorException(exception, key);
                }
                @Override public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key)
                {
                    RedisErrorException(exception, key);
                }
                @Override public void handleCacheClearError(RuntimeException exception, Cache cache)
                {
                    RedisErrorException(exception, null);
                }
            };
            return cacheErrorHandler;
        }
        protected void RedisErrorException(Exception exception,Object key)
        {
            log.error("redis异常:key=[{}], exception={}", key, exception.getMessage());
        }
        @Bean
        public RedisCacheConfiguration redisCacheConfiguration() {
            Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
            ObjectMapper om = new ObjectMapper();
            om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
            om.disable(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS);
            om.registerModule(new JavaTimeModule());
            jackson2JsonRedisSerializer.setObjectMapper(om);
    
            RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair
                    .fromSerializer(jackson2JsonRedisSerializer);
    
            RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                    .entryTtl(Duration.ofSeconds(redisKeyTtl))
                    .serializeValuesWith(pair);
    
            return redisCacheConfiguration;
        }
        @Bean
        public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
            //初始化一个RedisCacheWriter
            RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
            //初始化RedisCacheManager
            RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, redisCacheConfiguration());
            return cacheManager;
        }
    }
    

    使用:
    @Cacheable(cacheNames = "goodsCate", key = "'cateList'")
    @CacheEvict(cacheNames = "goodsCate",key = "'cateList'", allEntries = true)
    注解需要加在public方法之上,注意这里有个坑,本类中使用此方法的时候,必须通过spring的自动注入,将自己注入,纳入spring管理后,通过注入的变量来调用此方法才会起效。

    相关文章

      网友评论

          本文标题:spring boot 2.1.2.RELEASE整合cache

          本文链接:https://www.haomeiwen.com/subject/ebuucctx.html