Redis supports the publish/subscribe message queue mechanism. Jedis provides a Java client to access redis. This article describes how to use Jedis to implement simple message queues and transmit objects.
Redis supports publishing and subscription. The basic commands include publish and subscribe. In Jedis, there is a corresponding Java method, and only string messages can be published. To transmit objects, You need to serialize the objects and encapsulate them into strings for processing. After the object is serialized, it can only be a byte stream. It is difficult to encapsulate the object into a string. For details, refer to the following code.
Implement three classes: publish, subscribe, and object class to be passed.
Entity class:
Public class bean implements serializable {// the serialization interface private string name; Public String getname () {return name;} public void setname (string name) {This. name = Name ;}}
Publish class:
Public class testpub {public static void main (string [] ARGs) {Jedis = new Jedis ("127.0.0.1"); try {bean = new bean (); bean. setname ("test"); // use objectoutputstream and bytearrayoutputstream to convert an object into a word-based throttling; baos = new bytearrayoutputstream (); objectoutputstream OOS = new objectoutputstream (baos. writeobject (bean); string msg1 = baos. tostring ("ISO-8859-1"); // specifies the character set to decode the byte stream into a string, otherwise at the time of subscription . // Msg1 = urlencoder. encode (msg1, "UTF-8"); Jedis. Publish ("foo", msg1);} catch (exception e ){}}}
Subscribe class:
Public class testsub {public static void main (string [] ARGs) {Jedis = new Jedis ("127.0.0.1"); jedispubsub = new jedispubsub () {@ overridepublic void onunsubscribe (string channel, int publish) {}@ overridepublic void onsubscribe (string channel, int publish) {}@ overridepublic void onpunsubscribe (string pattern, int subscribedchannels) {}@ overridepublic void onpsubscribe (string pattern, int subscribedchannels) {}@ overridepublic void onpmessage (string pattern, string channel, string message) {}@ overridepublic void onmessage (string channel, string message) {try {bytearrayinputstream Bis = new bytearrayinputstream (message. getbytes ("ISO-8859-1"); // specify the character set here to encode the string into a byte array, where the character set must be consistent with the character set at release objectinputstream OIS = new objectinputstream (bis ); bean = (bean) Ois. readobject (); system. out. println (bean. getname ();} catch (exception e) {e. printstacktrace () ;}finally {}}; Jedis. subscribe (jedispubsub, "foo ");}}
Zookeeper
Jedis converts redis message queues, published object messages, byte arrays, and strings.