Java Implementation of redis publishing and subscription (easy to understand), javaredis
There are too many application scenarios for redis. Now we will introduce one of its major features, pub/sub ).
Features:
What is redis publishing and subscription (pub/sub )? Pub/Sub (means Publish, Subscribe) is the Publish and Subscribe function. In an event-based system, Pub/Sub is a widely used communication model. It uses events as the basic communication mechanism to provide a loosely coupled interaction mode required by large-scale systems: A subscriber (such as a client) subscribes to an event to express an event or a type of event that it is interested in receiving. A publisher (such as a server) can notify relevant subscriber of the event of interest to the subscriber at any time. Those who are familiar with design patterns should understand that this is very similar to the observer patterns in 23 design patterns.
Similarly, Redis pub/sub is a message communication mode, the main purpose is to remove the coupling between the message publisher and the message subscriber, Redis as a pub/sub server, message routing is enabled between the subscriber and the publisher.
It doesn't matter if you don't understand the above professional explanation. In fact, I didn't quite understand it either.
To put it simply, there is also a channel concept, which is the meaning of the channel. For example, if you subscribe to a bank channel and your funds change, you will receive information from the Bank through its channel. Here, you are passively receiving information, rather than asking for information from the bank. In this example, you are sub (subscriber), and the bank is pub (publisher ).
Application scenarios:
Before thinking that you will use the same technology, you must first understand where such a technology will be used and cannot blindly learn things.
Seeing the publishing and subscription features, it is no longer suitable for a simple real-time chat system. This is one of them. Of course, such a thing is rarely involved in development. Another common practice is that in our distributed architecture, we often encounter read/write splitting scenarios. During the write process, we can use redis to publish and subscribe, the write value is promptly released to each read program to ensure full data consistency. For another example, a blog website contains 100 fans who subscribe to you. When you publish new articles, you can push messages to fans. In short, there are many scenarios that need to be mined ..
Review how java operates redis:
Redis is a cache database. It is also a C/S structure, that is, the client and the server. Generally, in java, we usually use jedis (client) when operating redis (server), the two must establish a connection, just like a database link. In relational databases, we usually maintain a connection pool, to reuse links, you can save time for establishing and closing connections. Therefore, in jedis, there is also a jedispool (jedis connection pool) concept. We use it to retrieve connections from the pool.
Code:
To use jedis to introduce dependencies first
<dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.9.0</version></dependency>
Create a Publisher (Publisher)
Public class Publisher extends Thread {private final JedisPool jedisPool; public Publisher (JedisPool jedisPool) {this. jedisPool = jedisPool;} @ Override public void run () {BufferedReader reader = new BufferedReader (new InputStreamReader (System. in); Jedis jedis = jedisPool. getResource (); // get a connection in the connection pool while (true) {String line = null; try {line = reader. readLine (); if (! "Quit ". equals (line) {jedis. publish ("mychannel", line); // push messages from the channel of mychannel} else {break ;}} catch (IOException e) {e. printStackTrace ();}}}}
Create another subscriber
Public class Subscriber extends JedisPubSub {public Subscriber () {}@ Override public void onMessage (String channel, String message) {// System is called when a message is received. out. println (String. format ("receive redis published message, channel % s, message % s", channel, message) ;}@ Override public void onSubscribe (String channel, int subscribedChannels) {// If you subscribe to a channel, System is called. out. println (String. format ("subscribe redis channel success, channel % s, subscribedChannels % d", channel, subscribedChannels) ;}@ Override public void onUnsubscribe (String channel, int subscribedChannels) {// The System is called when the subscription is canceled. out. println (String. format ("unsubscribe redis channel, channel % s, subscribedChannels % d", channel, subscribedChannels ));}}
Here, the subscriber needs to inherit JedisPubSub to override its three methods. The usage annotation has been written, which is very simple.
Here we just define a subscriber and subscribe to the Channel below.
Public class SubThread extends Thread {private final JedisPool jedisPool; private final Subscriber subscriber = new Subscriber (); private final String channel = "mychannel"; public SubThread (JedisPool jedisPool) {super ("SubThread"); this. jedisPool = jedisPool;} @ Override public void run () {System. out. println (String. format ("subscribe redis, channel % s, thread will be blocked", channel); Jedis j Edis = null; try {jedis = jedisPool. getResource (); // retrieves a connection jedis. subscribe (subscriber, channel); // subscribe through the subscribe api. The input parameter is the subscriber and channel name} catch (Exception e) {System. out. println (String. format ("subsrcibe channel error, % s", e);} finally {if (jedis! = Null) {jedis. close ();}}}}
Finally, write another test class to run it. When a message is input on the keyboard, the subscriber triggers the onMessage method.
Public class PubSubDemo {public static void main (String [] args) {// connect to the redis server JedisPool jedisPool = new JedisPool (new JedisPoolConfig (), "127.0.0.1", 6379); System. out. println (String. format ("redis pool is starting, redis ip % s, redis port % d", "127.0.0.1", 6379); SubThread subThread = new SubThread (jedisPool ); // subThread of the subscriber. start (); Publisher publisher = new Publisher (jedisPool); // publisher Publisher. start ();}}
View printed results
Attaches Code address https://github.com/fangyong1421/redis
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.