测试redis集群的两种方式:分片和哨兵
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisSentinelPool; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.ShardedJedis; import redis.clients.jedis.ShardedJedisPool; public class JedisSentinelTest { /**
* 哨兵模式链接redis
* @throws Exception
*/ public void jedisSentinelPool() throws Exception { Set<String> sentinels = new HashSet<String>(); sentinels.add("哨兵的ip和端口"); sentinels.add("哨兵的ip和端口"); sentinels.add("哨兵的ip和端口"); JedisSentinelPool jedisSentinelPool = new JedisSentinelPool("master的别名", sentinels,"密码"); Jedis jedis = null; try { jedis = jedisSentinelPool.getResource(); jedis.set("hello", "world"); String value = jedis.get("hello"); System.out.println(value); } catch (Exception e) { System.out.println(e); } finally { if (jedis != null) try { jedis.close(); jedisSentinelPool.close(); } catch (Exception e) { e.printStackTrace(); } } } /**
* 分片模式链接
*/ public static void jedisTest(){ JedisPoolConfig jedisConfig = new JedisPoolConfig(); jedisConfig.setMaxIdle(20); jedisConfig.setTestOnBorrow(false); JedisShardInfo info79 = new JedisShardInfo("IP","端口"); JedisShardInfo info81 = new JedisShardInfo("IP","端口"); JedisShardInfo info80 = new JedisShardInfo("IP","端口"); info79.setPassword("密码"); info80.setPassword("密码"); info81.setPassword("密码"); List<JedisShardInfo> shards = new ArrayList<>(); shards.add(info79); shards.add(info80); shards.add(info81); ShardedJedisPool shardedJedisPool = new ShardedJedisPool(jedisConfig, shards); ShardedJedis ShardedJedis = null; try { ShardedJedis = shardedJedisPool.getResource(); } catch (Exception e) { e.printStackTrace(); } finally{ ShardedJedis.close(); shardedJedisPool.close(); } ShardedJedis.set("test", "测试"); String aaa = ShardedJedis.get("test"); System.out.println(aaa); } public static void main(String args[]){ jedisTest(); } }
原文:https://blog.csdn.net/qq_14823007/article/details/78820444