ShardedJedis (distributed) usage in Jedis (1), jedisshardedjedis

Source: Internet
Author: User

ShardedJedis (distributed) usage in Jedis (1), jedisshardedjedis

Redis was used as a cache service in the original project. At the beginning, only one Redis instance was used to meet the service requirements. As the project continued slowly, it was found that one could not meet the existing project requirements, because Redis operations are atomic, sometimes reading and writing cache results in a reduction in query efficiency. But because we still use 2. in Version X, there is still no cluster function (Redis author has added the cluster function in version 3.0), so only 2. in Version x, ShardedJedis is used to implement distributed caching.

ShardedJedis is throughConsistent hashTo implement distributed cache, and allocate different keys to different redis servers through certain policies, so as to achieve horizontal scaling. So how is ShardedJedis implemented internally? The article will explain it slowly.

 

1. ShardedJedis usage

The usage of ShardedJedis is different from that of Jedis in configuration. The usage of ShardedJedis is similar to that of Jedis.Multi-command operations are not supported,Commands such as mget, mset, and brpop that can operate multiple keys at a time after redis commands. For details, refer to the commands under Jedis.MultiKeyCommandsThis class contains all the multi-command operations. The author of Redis has filtered out these commands from ShardedJedis and cannot call these methods during use.

Now let's look at the basic usage.

 

// Configure JedisPoolConfig poolConfig = new JedisPoolConfig (); poolConfig. setMaxTotal (2); poolConfig. setMaxIdle (1); poolConfig. setMaxWaitMillis (2000); poolConfig. setTestOnBorrow (false); poolConfig. setTestOnReturn (false); // set the Redis information String host = "127.0.0.1"; JedisShardInfo shardInfo1 = new JedisShardInfo (host, 6379,500); shardInfo1.setPassword ("test123 "); export shardInfo2 = new JedisShardInfo (host, 6380,500); shardInfo2.setPassword ("test123"); JedisShardInfo shardInfo3 = new JedisShardInfo (host, 6381,500); shardInfo3.setPassword ("test123 "); // initialize the ShardedJedisPool List <JedisShardInfo> infoList = Arrays. asList (shardInfo1, shardInfo2, shardInfo3); jsonjedispool = new topology (poolConfig, infoList); // other operations such as query ShardedJedis jedis = null; try {jedis = jedisPool. getResource (); jedis. set ("test", "test"); jedis. set ("test1", "test1"); String test = jedis. get ("test"); System. out. println (test );......} finally {// close after use and return it to the connection pool
If (jedis! = Null ){
    jedis.close();
    } }

 

 

After jedis is obtainedBe sure to disable, Which is the same as using the database connection pool. Put it in the finally block to ensure that jedis is disabled.

Ps:If you use jdk 1.7 or later, you can use jdk 1.7.Try-with-resourcesStatement

 

       try(ShardedJedis jedis = jedisPool.getResource()) {            jedis.set("test", "test");            jedis.set("test1", "test1");            String test = jedis.get("test");            System.out.println(test);        }

 

Try-with-resourcesThe effect is the same as what we wrote above, but the jedis. close () syntax will help us call it. It will callTry-with-resourcesStatement.CloseableInterface object close method (like ShardedJedis above), we often use this method for database Connection and some input and output streams.

 

From the code point of view, in addition to InitializationShardedJedisPoolYou need to add multiple Redis server information. Other information is similar to that used by Jedis.

During initializationShardedJedisPoolYou can also importShardedJedisThe hash algorithm.MURMUR_HASHAndMD5Two algorithms are used by default.MURMUR_HASH(You can viewRedis. clients. util. HashingClass to view related information)

You can also inputKeyTagPatternTo specify the key distribution policy.KeyTagPatternKey (through regular expression matching) will be placed in the same redis. By default, key is directly used for determination. Redis comes withSharded.KeyTagPattern, As shown below

 

Pattern DEFAULT_KEY_TAG_PATTERN = Pattern.compile("\\{(.+?)\\}");

 

We can use the following code for actual testing.

ShardedJedis jedis = jedisPool. getResource ();

Jedis. set ("cnblog", "cnblog"); jedis. set ("redis", "redis"); jedis. set ("test", "test"); jedis. set ("123456", "1234567"); Client client1 = jedis. getShard ("cnblog "). getClient (); Client client2 = jedis. getShard ("redis "). getClient (); Client client3 = jedis. getShard ("test "). getClient (); Client client4 = jedis. getShard ("123456 "). getClient (); // the server on which the key is printed. out. println ("cnblog in server:" + client1.getHost () + "and port is:" + client1.getPort (); System. out. println ("redis in server:" + client2.getHost () + "and port is:" + client2.getPort (); System. out. println ("test in server:" + client3.getHost () + "and port is:" + client3.getPort (); System. out. println ("123456 in server:" + client4.getHost () + "and port is:" + client4.getPort ());

 

 

View output content:

We can see that the four keys we saved, cnblog and redis are in the same redis server, and the other two are in another redis server.

ShardedJedis uses a consistent hash algorithm to determine the storage location of each key. The specific calculation method is as follows: in the next article, we will study the source code of Jedis.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.