1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
这里要注意的是Lettuce是SpringBoot 2.x后才使用的,之前使用的是Jedis作为连接池,请注意自己项目的SpringBoot版本。
2、RedisConfig配置类
package controller;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.ReadFrom;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.DefaultClientResources;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import javax.annotation.Resource;
import java.time.Duration;
@Configuration
public class RedisConfig extends CachingConfigurerSupport{
@Resource
private RedisProperties redisProperties;
public GenericObjectPoolConfig<?> genericObjectPoolConfig(RedisProperties.Pool properties) {
GenericObjectPoolConfig<?> config = new GenericObjectPoolConfig<>();
config.setMaxTotal(properties.getMaxActive());
config.setMaxIdle(properties.getMaxIdle());
config.setMinIdle(properties.getMinIdle());
if (properties.getTimeBetweenEvictionRuns() != null) {
config.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRuns().toMillis());
}
if (properties.getMaxWait() != null) {
config.setMaxWaitMillis(properties.getMaxWait().toMillis());
}
return config;
}
@Bean
public DefaultClientResources lettuceClientResources() {
return DefaultClientResources.create();
}
@Bean(destroyMethod = "destroy")
public LettuceConnectionFactory lettuceConnectionFactory(ClientResources clientResources) {
//开启 自适应集群拓扑刷新和周期拓扑刷新
ClusterTopologyRefreshOptions clusterTopologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
// 开启全部自适应刷新
.enableAllAdaptiveRefreshTriggers() // 开启自适应刷新,自适应刷新不开启,Redis集群变更时将会导致连接异常
// 自适应刷新超时时间(默认30秒)
//默认关闭开启后时间为30秒
.adaptiveRefreshTriggersTimeout(Duration.ofSeconds(15))
// 开周期刷新
// 默认关闭开启后时间为60秒 ClusterTopologyRefreshOptions.DEFAULT_REFRESH_PERIOD 60 .enablePeriodicRefresh(Duration.ofSeconds(2)) = .enablePeriodicRefresh().refreshPeriod(Duration.ofSeconds(2))
.enablePeriodicRefresh(Duration.ofSeconds(15))
.build();
// https://github.com/lettuce-io/lettuce-core/wiki/Client-Options
ClientOptions clientOptions = ClusterClientOptions.builder()
.topologyRefreshOptions(clusterTopologyRefreshOptions)
.build();
LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
.clientResources(clientResources)
.poolConfig(genericObjectPoolConfig(redisProperties.getLettuce().getPool()))
.readFrom(ReadFrom.MASTER_PREFERRED)
.clientOptions(clientOptions)
//默认RedisURI.DEFAULT_TIMEOUT 60
.commandTimeout(redisProperties.getTimeout())
.build();
RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration(redisProperties.getCluster().getNodes());
clusterConfiguration.setPassword(RedisPassword.of(redisProperties.getPassword()));
// clusterConfiguration.setMaxRedirects(redisProperties.getCluster().getMaxRedirects());
return new LettuceConnectionFactory(clusterConfiguration, clientConfig);
}
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
StringRedisSerializer serializer = new StringRedisSerializer();
redisTemplate.setDefaultSerializer(serializer);
redisTemplate.setKeySerializer(serializer);
redisTemplate.setValueSerializer(serializer);
/**必须执行这个函数,初始化RedisTemplate*/
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
3、yml文件配置
spring:
redis:
cluster:
nodes[0]: 10.111.111.111:6379
lettuce:
##Redis服务器连接密码(默认为空)
# password:
##连接池最大连接数(使用负值表示没有限制)
pool:
max-active: 8
#连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1
#连接池中的最大空闲连接
max-idle: 8
#连接池中的最小空闲连接
min-idle: 0
#连接超时时间(毫秒)
timeout: 30000
4、遇到的几个小坑
错误1:
template not initialized; call afterPropertiesSet() before using it
解决方法就是,使用redisTemplate的时候,采用@Autowired注入的方式,不要直接new 出来
错误2:
ERR This instance has cluster support disabled
这个是因为redis没有开启集群模式,在安装redis的目录找到redis配置文件redis.conf
,里面会找到配置
# cluster-enabled yes
把注释去掉,然后重启就可以了。
错误3:
Cannot determine a partition to read for slot
这个是因为开启redis集群后,但是slot未分配,解决方式是在redis服务器上执行:
redis-cli --cluster fix 10.111.111.111:6379 -a 123456(密码使用自己配置的)
中途弹出Fix these slots by covering with a random node? (type 'yes' to accept):
输入yes即可。