Reids Implementing the Subscribe/Publish feature

Source: Internet
Author: User
Tags redis thread redis server

A publish Subscription (PUB/SUB) is a message communication pattern that is primarily designed to decouple the coupling between a message publisher and a message subscriber, which is similar to the observer pattern in design patterns. Pub/sub not only solves the direct code level coupling between publishers and subscribers, but also solves the coupling between the two on the physical deployment. As a pub/sub server, Redis serves as a message routing feature between subscribers and publishers. Subscribers can subscribe to Redis server with the subscribe and Psubscribe commands for the type of message they are interested in, and Redis calls the message type channel. When a publisher sends a specific type of message to Redis server through the Publish command. All clients subscribing to this message type receive this message. The delivery of the message here is many-to-many. A client can subscribe to multiple channel, or it can send messages to multiple channel.

Introducing the Jedis client:

<dependency>
  		<groupId>redis.clients</groupId>
  		<artifactid>jedis</artifactid >
  		<version>2.3.1</version>
  	</dependency>
Code implementation:

1. Message Listener Redispubsublistener.java

Package Cn.slimsmart.redis.demo;

Import Redis.clients.jedis.JedisPubSub; Publish a subscription message listens to public class Redispubsublistener extends Jedispubsub {//Gets the subscribed message after processing @Override public void OnMessage (stri
	NG Channel, String message) {System.out.println ("onmessage:channel[" + Channel + "], message[" + message + "]"); Processing @Override public void onpmessage (string pattern, string channel, String message) after getting the message subscribed by expression {System
	. OUT.PRINTLN ("onpmessage:pattern[" + pattern + "],channel[" + Channel + "], message[" + message + "]"); }//Initialize the process of subscribing by expression @Override public void Onpsubscribe (String channel, int subscribedchannels) {System.out.pri
	Ntln ("onsubscribe:channel[" + Channel + "]," + "subscribedchannels[" + Subscribedchannels + "]"); }//Cancel the process of subscribing by expression @Override public void Onpunsubscribe (String channel, int subscribedchannels) {System.out.pri
	Ntln ("onunsubscribe:channel[" + Channel + "]," + "subscribedchannels[" + Subscribedchannels + "]"); }//InitializationThe processing at the time of subscription @Override public void Onsubscribe (String pattern, int subscribedchannels) {System.out.println ("Onpunsubscribe
	: pattern["+ pattern +"], "+" subscribedchannels["+ Subscribedchannels +"] "); }//Unsubscribe processing @Override public void Onunsubscribe (String pattern, int subscribedchannels) {System.out.println ("OnP
	subscribe:pattern["+ pattern +"], "+" subscribedchannels["+ Subscribedchannels +"] "); }
}
2. Message Release Publisher.java

Package Cn.slimsmart.redis.demo;

Import Redis.clients.jedis.Jedis;

Publish message public
class Publisher {public
	void publish (Final Jedis redisclient) {
		new Thread (new Runnable () {
   @SuppressWarnings ("static-access")
			@Override public
			void Run () {
				try {
					thread.currentthread (). Sleep (+);
				} catch (Interruptedexception e) {
					e.printstacktrace ();
				}
				System.out.println ("Release: Log");
				Redisclient.publish ("Log.debug", "Log is Debug.");
				Redisclient.publish ("Log.info", "Log is info.");
				Redisclient.publish ("Log.error", "Log is error.");
			}
		). Start ();
	}
}
3. Message Subscription

Package Cn.slimsmart.redis.demo;

Import Redis.clients.jedis.Jedis;

Subscription message public
class Subscriber {public
	void Psub (Final Jedis redisclient, final Redispubsublistener listener) { C4/>new Thread (New Runnable () {
			@Override public
			void Run () {
				System.out.println ("subscription: Log.debug");
				Subscribe to get information on Lister's OnMessage (...) method to process
				//Subscribe to multiple channels
				//Redisclient.subscribe (Listener, "Log.debug", "Log.info");
				Redisclient.subscribe (Listener, New string[]{"Log.debug", "Log.info"});
				Redisclient.psubscribe (Listener, new string[] {"log.*"});//Set channel with pattern matching
			}
		}). Start ();}
}
4. Start the service Main.java

Package Cn.slimsmart.redis.demo;

Import Redis.clients.jedis.Jedis;
Import Redis.clients.jedis.JedisPool;
Import Redis.clients.jedis.JedisPoolConfig;

public class Main {public
	static void Main (string[] args) {
		jedispoolconfig config = new Jedispoolconfig ();  
		Config.setmaxidle (0);
		Config.setmaxtotal (a);
		Config.setmaxwaitmillis (+);
		Config.settestonborrow (true);
		  
		Create Connection pool
		jedispool pool = new Jedispool (config, "192.168.100.205", 6379);  
		
		Get client
		Jedis redisClient1 = Pool.getresource ();  
		Jedis RedisClient2 = Pool.getresource ();  
		Redispubsublistener listener = new Redispubsublistener ();  
		
		 Publisher pub = new publisher ();  
		 Pub.publish (RedisClient2); Publish a channel  
		  
		 subscriber sub = new Subscriber ();  
		 Sub.psub (redisClient1, listener); Subscribe to a channel  
	}
}

5. Run main to see the results

Subscription: Log.debug
onsubscribe:channel[log.*],subscribedchannels[1]
posted: Log
onpmessage:pattern[log.*], Channel[log.debug], Message[log is debug.]
Onpmessage:pattern[log.*],channel[log.info], Message[log is info.]
Onpmessage:pattern[log.*],channel[log.error], Message[log is error.]
Or use REDIS-CLI on Redis clients

Input: Publish Log.warn "log is warn" to observe the receiving message.


Combined with Spring reference: http://blog.csdn.net/zhu_tianwei/article/details/17752553

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.