1,pom依赖添加:
2,application.properties中配置:
#redis cluster
redis.cache.clusterNodes=120.125.122.103:5000,120.125.122.103:5001,120.125.122.103:5002,120.125.122.103:5003,120.125.122.103:5004,120.125.122.103:5005
redis.cache.commandTimeout=5000
#unit:second
redis.cache.expireSeconds=120
3,新增类RedisProperties JedisClusterConfig,核心代码如下:
@Component
@ConfigurationProperties(prefix = "redis.cache")
public class RedisProperties {
private int expireSeconds;
private String clusterNodes;
private int commandTimeout;
}
@Configuration
public class JedisClusterConfig {
@Autowired
private RedisProperties redisProperties;
/**
* 注意:
* 这里返回的JedisCluster是单例的,并且可以直接注入到其他类中去使用
* @return
*/
@Bean
public JedisCluster getJedisCluster() {
String[] serverArray = redisProperties.getClusterNodes().split(",");//获取服务器数组(这里要相信自己的输入,所以没有考虑空指针问题)
Set
for (String ipPort : serverArray) {
String[] ipPortPair = ipPort.split(":");
nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
}
return new JedisCluster(nodes, redisProperties.getCommandTimeout());
}
}
特别注意:@ConfigurationProperties(prefix = "redis.cache") 中redis.cache要和application.properties中的前缀对应。
4,使用:
@Autowired
private JedisCluster jc ;