Java教程

Java连接Redis集群

本文主要是介绍Java连接Redis集群,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

导入maven依赖

<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
</dependency>

测试类

package com.boot.business;

import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Set;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

public class AppTest {
  public static void main(String[] args) {
    JedisPoolConfig poolConfig = new JedisPoolConfig();
    // 最大连接数
    poolConfig.setMaxTotal(1);
    // 最大空闲数
    poolConfig.setMaxIdle(1);
    // 最大允许等待时间,如果超过这个时间还未获取到连接,则会报JedisException异常:
    // Could not get a resource from the pool
    poolConfig.setMaxWaitMillis(1000);
    Set<HostAndPort> nodes = new LinkedHashSet<HostAndPort>();
    nodes.add(new HostAndPort("192.168.33.159", 7001));
    nodes.add(new HostAndPort("192.168.33.159", 7002));
    nodes.add(new HostAndPort("192.168.33.159", 7003));
    nodes.add(new HostAndPort("192.168.33.159", 7004));
    nodes.add(new HostAndPort("192.168.33.159", 7005));
    nodes.add(new HostAndPort("192.168.33.159", 7006));
    JedisCluster cluster = new JedisCluster(nodes, poolConfig);
    String name = cluster.get("name");
    System.out.println(name);
    cluster.set("age", "18");
    System.out.println(cluster.get("age"));
    try {
      cluster.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

 

这篇关于Java连接Redis集群的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!