Redis Java客户端-通过原生jedis和SpringBoot操作Redis集群

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:
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值