Redis client development kit: Jedis learning-advanced application, redisjedis
Transactions
In Jedis, the transaction is written in the transaction code block for redis operations, as shown below. The transaction between multi and exec is a specific transaction.
jedis.watch (key1, key2, ...);Transaction t = jedis.multi();t.set("foo", "bar");t.exec();
In addition, the value cannot be obtained through the Jedis object within the Transaction, but it can be obtained through the Transaction object, as shown below:
Package cn.edu. hdu. jedisdemo; import java. util. set; import redis. clients. jedis. jedis; import redis. clients. jedis. jedisPool; import redis. clients. jedis. jedisPoolConfig; import redis. clients. jedis. response; import redis. clients. jedis. transaction; public class App {public static void main (String [] args) {JedisPool pool = new JedisPool (new JedisPoolConfig (), "localhost"); // Jedis implements Closable. bytes Ce, the jedis instance will be // auto-closed after the last statement. try (Jedis jedis = pool. getResource ()){///... do stuff here... for example Transaction t = jedis. multi (); t. set ("fool", "bar"); // jedis. get ("fool"); // error, Cannot use Jedis when in Multi. please use Transation or reset jedis state. response <String> result1 = t. get ("fool"); t. zadd ("foo", 1, "barowitch"); t. zadd ("foo", 0, "bar Insky "); t. zadd ("foo", 0, "barikoviev"); Response <Set <String> sose = t. zrange ("foo", 0,-1); t.exe c (); // dont forget it String foolbar = result1.get (); // use Response. get () to retrieve things from a Response int soseSize = sose. get (). size (); // on sose. get () you can directly call Set methods! // List <Object> allResults = t.exe c (); // you cocould still get all // results at once, as before System. out. println (foolbar); System. out. println (soseSize );}///... when closing your application: pool. close ();}}
Note: The getresponse of the responseobject must be called after the transaction execute. Before the t.exe c () method is executed, the Response object does not contain the result.
MPs queue
Sometimes, we need to send multiple commands. An efficient method is to use pipelines;
The pipeline can send multiple commands at a time and return the results at a time after execution, when each command in a group of commands does not depend on the execution result of the previous command, the command can be issued together through the pipeline;
Pipelines can reduce the number of communications between clients and redis and provide performance.
Example:
Pipeline p = jedis.pipelined();p.set("fool", "bar"); p.zadd("foo", 1, "barowitch"); p.zadd("foo", 0, "barinsky"); p.zadd("foo", 0, "barikoviev");Response<String> pipeString = p.get("fool");Response<Set<String>> sose = p.zrange("foo", 0, -1);p.sync(); int soseSize = sose.get().size();Set<String> setBack = sose.get();Publish/subscribe to messages
First, create a JedisPubSub object, and then call the subscribe method using the Jedis object. This method requires passing in the JedisPubSub object;
MyListener listener = new MyListener (); // The listener is a JedisPubSub object, and the listener class jedis. subscribe (listener, "channel01 ");
Publish messages
Call the publish method of Jedis to publish a message;
jedis.publish(channel, message)
Note: The subscribe method is a blocking operation, and the same Jedis object cannot be used for publishing and subscription.
A complete example
Listener event class:
package cn.edu.hdu.jedisdemo;import redis.clients.jedis.JedisPubSub;class MyListener extends JedisPubSub { public void onMessage(String channel, String message) { System.out.println("get a msg: " + "channel=" + channel + ", message=" + message); } public void onSubscribe(String channel, int subscribedChannels) { System.out.println("channel:" + channel + ", subscribedChannels:" + subscribedChannels); } public void onUnsubscribe(String channel, int subscribedChannels) { System.out.println("channel:" + channel + ", subscribedChannels:" + subscribedChannels); } public void onPSubscribe(String pattern, int subscribedChannels) { System.out.println("pattern:" + pattern + ", subscribedChannels:" + subscribedChannels); } public void onPUnsubscribe(String pattern, int subscribedChannels) { System.out.println("pattern:" + pattern + ", subscribedChannels:" + subscribedChannels); } public void onPMessage(String pattern, String channel, String message) { System.out.println("pattern:" + pattern + ", channel:" + channel + ", message:" + message); }}
Main method:
Package cn.edu. hdu. jedisdemo; import java. util. date; import java. util. concurrent. timeUnit; import redis. clients. jedis. jedis; import redis. clients. jedis. jedisPool; import redis. clients. jedis. jedisPoolConfig; public class App {public static void main (String [] args) {final JedisPool pool = new JedisPool (new JedisPoolConfig (), "localhost "); // two subscribers new Thread (new Runnable () {@ Override public void run () {Jedis jedis = pool. getResource (); MyListener listener = new MyListener (); jedis. subscribe (listener, "channel01 ");}}). start (); new Thread (new Runnable () {@ Override public void run () {Jedis jedis = pool. getResource (); MyListener listener = new MyListener (); // The listener is a JedisPubSub object, and the listening class is jedis. subscribe (listener, "channel01 ");}}). start (); // a publisher new Thread (new Runnable () {@ Override public void run () {// note, the jedis object used for subscription cannot be the same as the jedis object used for publishing. If the Jedis object is not used for subscription, the jedis = pool error is returned. getResource (); while (true) {try {TimeUnit. SECONDS. sleep (1);} catch (InterruptedException e) {e. printStackTrace ();} String msg = new Date (). toLocaleString (); System. out. println ("publish a msg:" + msg); jedis. publish ("channel01", msg );}}}). start (); // pool. close ();}}
Execution result:
Channel: channel01, subscribedChannels: 1
Channel: channel01, subscribedChannels: 1
Publish a msg: 10:03:42
Get a msg: channel = channel01, message = 10:03:42
Get a msg: channel = channel01, message = 10:03:42
Publish a msg: 10:03:43
Get a msg: channel = channel01, message = 10:03:43
Get a msg: channel = channel01, message = 10:03:43
Publish a msg: 10:03:44
Get a msg: channel = channel01, message = 10:03:44
Get a msg: channel = channel01, message = 2016-7-20 10:03:44 distributed ShardedJedis
ShardedJedis uses a consistent hash algorithm to determine the storage location of each key, which is mainly used to share the pressure on the server.
A simple example:
First, enable three redis servers and use different ports (copy three copies and use different configuration files): 6379, 6380, and 6381
Then, write the test code:
Package cn.edu. hdu. jedisdemo; import java. util. arrays; import java. util. list; import redis. clients. jedis. client; import redis. clients. jedis. jedisPoolConfig; import redis. clients. jedis. jedisShardInfo; import redis. clients. jedis. shardedJedis; import redis. clients. jedis. shardedJedisPool; public class App {public static void main (String [] args) {// set 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"; region shardInfo1 = new JedisShardInfo (host, 6379,500); JedisShardInfo shardInfo2 = new JedisShardInfo (host, 6380,500 ); jedisShardInfo shardInfo3 = new JedisShardInfo (host, 6381,500); // initialize the ShardedJedisPool List <JedisShardInfo> infoList = Arrays. asList (shardInfo1, shardInfo2, shardInfo3); ShardedJedisPool jedisPool = new ShardedJedisPool (poolConfig, infoList); // some basic operations try (ShardedJedis jedis = jedisPool. getResource () {jedis. set ("test", "test"); String test = jedis. get ("test"); System. out. println (test);} // view ShardedJedis jedis = jedisPool. getResource (); jedis. set ("1111", "1111"); jedis. set ("2222", "2222"); jedis. set ("3333", "3333"); jedis. set ("4444", "4444"); Client client1 = jedis. getShard ("1111 "). getClient (); Client client2 = jedis. getShard ("2222 "). getClient (); Client client3 = jedis. getShard ("3333 "). getClient (); Client client4 = jedis. getShard ("4444 "). getClient (); // the server on which the key is printed. out. println ("1111 in server:" + client1.getHost () + "and port is:" + client1.getPort (); System. out. println ("2222 in server:" + client2.getHost () + "and port is:" + client2.getPort (); System. out. println ("3333 in server:" + client3.getHost () + "and port is:" + client3.getPort (); System. out. println ("4444 in server:" + client4.getHost () + "and port is:" + client4.getPort ());
Jedis. close (); jedisPool. close ();}}
View output results:
Test
1111 in server: 127.0.0.1 and port is: 6380
2222 in server: 127.0.0.1 and port is: 6379
3333 in server: 127.0.0.1 and port is: 6381
4444 in server: 127.0.0.1 and port is: 6381
References:
Https://github.com/xetorthio/jedis/wiki/AdvancedUsage
Http://www.cnblogs.com/coder2012/p/4401153.html
Http://blog.csdn.net/lihao21/article/details/48370687
Http://www.cnblogs.com/vhua/p/redis_1.html