Redis java客户端操作集群
1. 使用Jedis java原生操作redis集群
public class RedisCluster {
public static void main(String[] args) {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(20);
jedisPoolConfig.setMaxIdle(10);
jedisPoolConfig.setMinIdle(5);
Set<HostAndPort> clusterNodes = new HashSet<HostAndPort>();
clusterNodes.add(new HostAndPort("192.168.0.101", 8001));
clusterNodes.add(new HostAndPort("192.168.0.101", 8004));
clusterNodes.add(new HostAndPort("192.168.0.102", 8002));
clusterNodes.add(new HostAndPort("192.168.0.102", 8005));
clusterNodes.add(new HostAndPort("192.168.0.103", 8003));
clusterNodes.add(new HostAndPort("192.168.0.103", 8006));
JedisCluster jedisClusterPool = new JedisCluster(clusterNodes, 6000, 5000, 10, "allen", jedisPoolConfig);
System.out.println(jedisClusterPool.set("jedisClusterTest", "hello world jedisClusterTest Tset"));
System.out.println(jedisClusterPool.get("jedisClusterTest"));
}
}
执行结构:
OK
hello world jedisClusterTest Tset
Process finished with exit code 0
从集群上查看设置结果:
192.168.0.103:8003> keys *
1) "SentinelTest2"
2) "jedisClusterTest"
192.168.0.103:8003> get jedisClusterTest
"hello world jedisClusterTest Tset"
2. 使用springboot操作redis集群
1. 启动类:
@SpringBootApplication
public class ApplicationStarter {
public static void main(String[] args) {
SpringApplication.run(ApplicationStarter.class,args);
}
}
2. 服务类:
@RestController
public class IndexController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
//@RequestMapping("/SentinelTest")
@RequestMapping("/ClusterRedisTest")
public void testSentinel() throws InterruptedException {
int i = 1;
while(true){
try {
stringRedisTemplate.opsForValue().set("SentinelTest2", i++ + "");
System.out.println("successed set SentinelTest2 to " + i);
Thread.sleep(1000);
}catch (Exception e){
System.out.println(e);
}
}
}
}
Spring 配置redis cluster
server:
port: 8080
spring:
redis:
database: 0
timeout: 3000
password: allen
cluster:
nodes: 192.168.0.101:8001,192.168.0.101:8004,192.168.0.102:8002,192.168.0.102:8005,192.168.0.103:8003,192.168.0.103:8006
lettuce:
pool: