springboot中redis做緩存時的配置


import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
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.connection.RedisConnectionFactory;

import java.time.Duration;
import java.util.Map;

/**
* @author cjy
* @description
* @date 2019/12/24
**/
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

private static Logger LOGGER = LoggerFactory.getLogger(RedisConfig.class);

/**
* 緩存管理器
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory lettuceConnectionFactory) {
RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
// 設置緩存管理器管理的緩存的默認過期時間
.entryTtl(Duration.ofMinutes(5))
// 不緩存空值
.disableCachingNullValues();
Map<String, RedisCacheConfiguration> configMap = ImmutableMap.<String, RedisCacheConfiguration>builder()
.put("your cacheName", RedisCacheConfiguration.defaultCacheConfig().entryTtl(
Duration.ofMinutes(1)
))
.build();
return RedisCacheManager.builder(lettuceConnectionFactory)
.cacheDefaults(defaultCacheConfig)
.withInitialCacheConfigurations(configMap)
.build();
}

/**
* redis數據操作異常處理 這里的處理:在日志中打印出錯誤信息,但是放行
* 保證redis服務器出現連接等問題的時候不影響程序的正常運行,使得能夠出問題時不用緩存
*
* @return
*/
@Bean
@Override
public CacheErrorHandler errorHandler() {
return new CacheErrorHandler() {
@Override
public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) {
redisErrorException(exception, key);
}
@Override
public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
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);
}
};
}

private void redisErrorException(Exception exception, Object key) {
LOGGER.error("Redis exception: key={}", key, exception);
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM