连接腾讯云redis集群 Redis配置类RedisConfig.java 示例代码
时间: 2024-02-20 16:32:01 浏览: 146
以下是连接腾讯云 Redis 集群的配置类 RedisConfig.java 示例代码:
```java
import org.springframework.beans.factory.annotation.Value;
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.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
public class RedisConfig {
@Value("${spring.redis.cluster.nodes}")
private String clusterNodes;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.timeout}")
private int timeout;
@Bean
public JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(20);
jedisPoolConfig.setMaxIdle(10);
jedisPoolConfig.setMinIdle(5);
jedisPoolConfig.setMaxWaitMillis(10000);
jedisPoolConfig.setTestOnBorrow(true);
jedisPoolConfig.setTestOnReturn(true);
jedisPoolConfig.setTestWhileIdle(true);
return jedisPoolConfig;
}
@Bean
public RedisConnectionFactory redisConnectionFactory() {
RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
redisClusterConfiguration.setClusterNodes(getClusterNodes());
redisClusterConfiguration.setMaxRedirects(3);
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisClusterConfiguration, jedisPoolConfig());
jedisConnectionFactory.setPassword(getPassword());
jedisConnectionFactory.setTimeout(getTimeout());
return jedisConnectionFactory;
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory());
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
private String getClusterNodes() {
return clusterNodes;
}
private String getPassword() {
return password;
}
private int getTimeout() {
return timeout;
}
}
```
需要在 application.properties 或 application.yml 中添加以下配置:
```yaml
spring:
redis:
cluster:
nodes: <redis集群节点>
password: <密码>
timeout: <连接超时时间>
```
其中 `<redis集群节点>` 是 Redis 集群的节点地址,多个节点之间用逗号隔开,例如 `redis-1:6379,redis-2:6379`。`<密码>` 是 Redis 集群的密码,如果没有密码可以不填写。`<连接超时时间>` 是连接 Redis 集群的超时时间,单位为毫秒。
阅读全文