redis.host=192.168.126.129
redis.port=6379
redis.auth=123456
redis.nodes=192.168.126.129:6379:123456,192.168.126.129:6380:123456,192.168.126.129:6381:123456
package com.jt.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import java.util.ArrayList;
import java.util.List;
@Configuration
@PropertySource("classpath:/properties/redis.properties")
public class JedisConfig {
@Value("${redis.host}")
private String host;
@Value("${redis.port}")
private Integer port;
@Value("${redis.auth}")
private String paw;
@Value("${redis.nodes}")
private String nodes;
//配置单台的redis
@Bean
//@Scope("prototype")//设置为多例模式
public Jedis jedis() {
Jedis jd = new Jedis(host, port);
jd.auth(paw);
return jd;
}
//配置redis分片连接
@Bean
public ShardedJedis ShardedJedis() {
String[] node = nodes.split(",");
List<JedisShardInfo> list = new ArrayList();
for (String nod : node) {
String host = nod.split(":")[0];
int port = Integer.parseInt(nod.split(":")[1]);
String password = "";
//判断是否有密码字段
if (nod.split(":").length > 2) {
//有密码字段则设置 密码
password = nod.split(":")[2];
}
JedisShardInfo jedisShardInfo = new JedisShardInfo(host, port);
//没有密码则直接连接
if (password != "") {
jedisShardInfo.setPassword(password);
}
list.add(jedisShardInfo);
}
ShardedJedis shardedJedis = new ShardedJedis(list);
return shardedJedis;
}
}