Redis——jedisCluster连接Redis集群简单使用

maven导入jedis包(当前最新Official Releases 3.7.0):

		
		    redis.clients
		    jedis
		    3.7.0
		

先搭建Redis集群:

直接拿之前的集群来用:Redis——cluster集群_FlyLikeButterfly的博客-CSDN博客

Redis的虚拟机ip:192.168.1.31;6个Redis集群端口8001-8006;

集群关系:

Redis——jedisCluster连接Redis集群简单使用_第1张图片

 集群里的数据:

Redis——jedisCluster连接Redis集群简单使用_第2张图片

 测试Demo:

/**
 * 2021年11月5日上午9:50:22
 */
package testJedisCluster;

import java.time.Duration;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;

/**
 * @author XWF
 *
 */
public class TestJedisCluster {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Set jedisClusterNode = new HashSet<>();
		jedisClusterNode.add(new HostAndPort("192.168.1.31", 8001));
//		jedisClusterNode.add(new HostAndPort("192.168.1.31", 8002));
//		jedisClusterNode.add(new HostAndPort("192.168.1.31", 8003));
//		jedisClusterNode.add(new HostAndPort("192.168.1.31", 8004));
//		jedisClusterNode.add(new HostAndPort("192.168.1.31", 8005));
//		jedisClusterNode.add(new HostAndPort("192.168.1.31", 8006));
		int connectionTimeout = 3000;
		int soTimeout = 3000;
		int maxAttempts = 5;
		String password = "654321";
		GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig<>();
		poolConfig.setMaxIdle(100);
//		poolConfig.setMaxWait(Duration.ofMillis(10000));	//4.0.0-SNAPSHOT版本
		poolConfig.setMaxWaitMillis(10000);
		poolConfig.setTestOnBorrow(true);
		try (JedisCluster myCluster = new JedisCluster(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, password, poolConfig)) {
			System.out.println(myCluster.getClusterNodes().keySet());
			int i = 0;
			while(i < 10) {
				String key1 = String.valueOf((char)('a' + i));
				System.out.println(key1 + " : " + myCluster.get(key1));
				String key2 = String.valueOf((char)('A' + i)) + "{hashtagX}";
				System.out.println(key2 + " -> " + myCluster.get(key2));
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				i++;
			}
			System.out.println(myCluster.mget("A{hashtagX}", "B{hashtagX}", "xxx{hashtagX}xxx"));	//批量查询key的slot需要一样
//			System.out.println(myCluster.mget("a", "b"));	//异常:No way to dispatch this command to Redis Cluster because keys have different slots.
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

运行结果:

Redis——jedisCluster连接Redis集群简单使用_第3张图片

 jedisCluster可以自动发现节点,只要在启动的时候配置的节点列表有正常可用的,就可以获取到集群;

只配置8001节点,启动时8001正常,运行过程中停掉8001依然可以使用集群功能;

批量操作需要注意slot一致;

Jedis的git网址:https://github.com/redis/jedis

你可能感兴趣的:(redis,jedisCluster,jedis连接集群)