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

x33g5p2x  于2021-11-09 转载在 Redis  
字(2.5k)|赞(0)|评价(0)|浏览(285)

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

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

先搭建Redis集群:

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

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

集群关系:

集群里的数据:

测试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<HostAndPort> 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<Jedis> 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();
		}
	}

}

运行结果:

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

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

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

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

相关文章

微信公众号

最新文章

更多