spring boot 2.1.2.RELEASE整合cache和redis

針對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管理后,通過注入的變量來調(diào)用此方法才會起效。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容