一、SpringBoot 集成Redis 做缓存
1.1、 添加依赖
<!-- redis依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
//线程池
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.6.1</version>
</dependency>
1.2、配置文件(哨兵)
spring:
redis:
database: 0
sentinel:
master: 'mymaster'
nodes:
- "redis://127.0.0.1:26383"
- "redis://127.0.0.1:26382"
- "redis://127.0.0.1:26381"
# password
lettuce:
pool:
# 连接池最大连接数 默认8 ,负数表示没有限制
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认-1
max-wait: -1
# 连接池中的最大空闲连接 默认8
max-idle: 8
# 连接池中的最小空闲连接 默认0
min-idle: 0
redisson:
file: classpath:redisson.yml
1.3、 Redis 缓存配置
@Slf4j
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
private RedisSerializer serializer(){
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
// 将类型序列化到属性json字符串中
// objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
// 对于找不到匹配属性的时候忽略报错
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 不包含任何属性的bean也不报错
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
serializer.setObjectMapper(objectMapper);
return serializer;
}
/**
* 如使用注解的话需要配置cacheManager
*
* @return
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
//覆盖默认的序列化
RedisSerializer serializer = serializer();
//默认配置
RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration
.defaultCacheConfig()
//设置默认超过期时间是7天
.entryTtl(Duration.ofDays(7))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer));
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(defaultCacheConfig)
.build();
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
//覆盖默认的序列化
RedisSerializer serializer = serializer();
StringRedisSerializer stringRedisSerializer = StringRedisSerializer.UTF_8;
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
redisTemplate.setHashValueSerializer(serializer);
redisTemplate.setValueSerializer(serializer);
redisTemplate.setDefaultSerializer(serializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
@Override
public CacheErrorHandler errorHandler() {
// 异常处理,当Redis发生异常时,打印日志,但是程序正常走
log.info("初始化 -> [{}]", "Redis CacheErrorHandler");
CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
log.error("Redis occur handleCacheGetError:key -> [{}]", key, e);
}
@Override
public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
log.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e);
}
@Override
public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) {
log.error("Redis occur handleCacheEvictError:key -> [{}]", key, e);
}
@Override
public void handleCacheClearError(RuntimeException e, Cache cache) {
log.error("Redis occur handleCacheClearError:", e);
}
};
return cacheErrorHandler;
}
}
二、Spring 集成 Redisson
2.1、添加依赖
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.16.6</version>
</dependency>
2.2、redisson 配置
- redisson.yml (哨兵模式)
```yaml
sentinelServersConfig:
#空闲链接超时
idleConnectionTimeout: 10000
#连接超时
connectTimeout: 10000
# 超时
timeout: 3000
# 重试次数
retryAttempts: 3
# 重试间隔
retryInterval: 1500
# 失败重连间隔
failedSlaveReconnectionInterval: 3000
# 失败检查
failedSlaveCheckInterval: 60000
# 密码
password: null
subscriptionsPerConnection: 5
clientName: null
# 负载均衡
loadBalancer: !<org.redisson.connection.balancer.RoundRobinLoadBalancer> {}
subscriptionConnectionMinimumIdleSize: 1
subscriptionConnectionPoolSize: 50
slaveConnectionMinimumIdleSize: 24
slaveConnectionPoolSize: 64
masterConnectionMinimumIdleSize: 24
masterConnectionPoolSize: 64
readMode: "SLAVE"
subscriptionMode: "SLAVE"
sentinelAddresses:
- "redis://127.0.0.1:26383"
- "redis://127.0.0.1:26382"
- "redis://127.0.0.1:26381"
masterName: "mymaster"
database: 0
threads: 16
nettyThreads: 32
codec: !<org.redisson.codec.JsonJacksonCodec> {}
transportMode: "NIO"
三、参考
- https://docs.spring.io/spring-data/redis/docs/2.2.0.RELEASE/reference/html/#reference
- https://github.com/h-dj/Spring-Learning.git