本文主要是介绍redis学习(十七) 使用shardedJedis,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
使用shardedJedis
ShardedJedis是通过一致性哈希来实现分布式缓存的,通过一定的策略把不同的key分配到不同的redis server上,达到横向扩展的目的,废话不多说直接上一个测试代码吧,代码里会有注释。
代码github地址: github地址
public class ShareJedisTest {public static void main(String[] args) {//设置连接池的相关配置JedisPoolConfig poolConfig = new JedisPoolConfig();poolConfig.setMaxTotal(2);poolConfig.setMaxIdle(1);poolConfig.setMaxWaitMillis(2000);poolConfig.setTestOnBorrow(false);poolConfig.setTestOnReturn(false);//设置Redis信息String host = "192.168.72.128";JedisShardInfo shardInfo1 = new JedisShardInfo(host, 6379, 5000);JedisShardInfo shardInfo2 = new JedisShardInfo(host, 6381, 5000);//初始化ShardedJedisPoolList<JedisShardInfo> infoList = Arrays.asList(shardInfo1, shardInfo2);ShardedJedisPool jedisPool = new ShardedJedisPool(poolConfig, infoList);//进行查询等其他操作ShardedJedis jedis = null;try {jedis = jedisPool.getResource();jedis.set("test", "test");jedis.set("test1", "test1");jedis.set("test2", "test2");jedis.set("test3", "test3");jedis.set("test4", "test4");//查看具体key在哪个客户端Client client0 = jedis.getShard("test").getClient();Client client1 = jedis.getShard("test1").getClient();Client client2 = jedis.getShard("test2").getClient();Client client3 = jedis.getShard("test3").getClient();Client client4 = jedis.getShard("test4").getClient();System.out.println(client0.getHost() + ":" + client0.getPort());System.out.println(client1.getHost() + ":" + client1.getPort());System.out.println(client2.getHost() + ":" + client2.getPort());System.out.println(client3.getHost() + ":" + client3.getPort());System.out.println(client4.getHost() + ":" + client4.getPort());} finally {//使用后一定关闭,还给连接池if(jedis!=null) {jedis.close();}}}
}
上一篇 使用jedis执行lua脚本(实现一个对IP的限流)
这篇关于redis学习(十七) 使用shardedJedis的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!