How to configure a Spring Cloud Redis cluster?
To configure a Spring Cloud Redis cluster, the following steps need to be followed:
- Add the necessary dependencies for Redis in the pom.xml file.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- Configure the connection information for the Redis cluster in the application.properties file.
# Redis集群节点信息
spring.redis.cluster.nodes=127.0.0.1:7001,127.0.0.1:7002,127.0.0.1:7003
# Redis连接池配置
spring.redis.cluster.max-idle=8
spring.redis.cluster.min-idle=1
spring.redis.cluster.max-active=8
spring.redis.cluster.max-wait=3000
- Create a Redis configuration class for configuring RedisTemplate and the connection pool.
@Configuration
public class RedisConfig {
@Value("${spring.redis.cluster.nodes}")
private String clusterNodes;
@Value("${spring.redis.cluster.max-idle}")
private int maxIdle;
@Value("${spring.redis.cluster.min-idle}")
private int minIdle;
@Value("${spring.redis.cluster.max-active}")
private int maxActive;
@Value("${spring.redis.cluster.max-wait}")
private long maxWait;
@Bean
public RedisClusterConfiguration redisClusterConfiguration() {
RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(Arrays.asList(clusterNodes.split(",")));
return redisClusterConfiguration;
}
@Bean
public JedisConnectionFactory jedisConnectionFactory(RedisClusterConfiguration redisClusterConfiguration) {
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisClusterConfiguration);
return jedisConnectionFactory;
}
@Bean
public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
return redisTemplate;
}
@Bean
public RedisCacheManager redisCacheManager(RedisTemplate<String, Object> redisTemplate) {
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
redisCacheManager.setUsePrefix(true);
return redisCacheManager;
}
}
- Inject RedisTemplate where Redis is needed, allowing you to operate on a Redis cluster.
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void set(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
public boolean exists(String key) {
return redisTemplate.hasKey(key);
}
The configuration of using Redis cluster in Spring Cloud is now complete. It is important to note that the node information and connection pool settings of the Redis cluster can be modified according to specific circumstances.