There are too many application scenarios for redis. Now let me introduce one of its major features, publish subscription (pub/sub).
Feature introduction:
What is a publish subscription for redis (pub/sub)? The Pub/Sub function (means Publish, Subscribe) is the publishing and subscription function. In event-based systems, Pub/Sub is currently widely used communication model. It adopts events as the basic communication mechanism to provide a loosely coupled interaction model required by large-scale systems: a subscriber (such as a client) expresses an event or a type of event that it is interested in receiving in the form of event subscription; a publisher (such as a server) can notify relevant subscribers of events that the subscriber is interested in at any time. Friends who are familiar with design patterns should understand that this is very similar to the observer pattern among the 23 design patterns.
Similarly, Redis's pub/sub is a message communication mode, the main purpose is to uncouple the message publisher and message subscriber. As a pub/sub server, Redis plays the function of message routing between subscribers and publishers.
If you don’t understand the above professional explanation, it doesn’t matter, but I don’t understand it very much.
Simply put, there is also a concept of channel here, which means channel. For example, if you subscribe to a bank channel, when your funds change, you will accept that the bank will send you information through its channel. Here, you are passively receiving, rather than asking the bank for information. In this example, you are sub (subscriber), and the bank is pub (pub).
Project application scenarios:
I always thought that before you knew the same technology, you must first understand where such a technology will be used and you cannot learn things blindly.
Seeing the feature of publishing subscriptions, it is perfect for making a simple live chat system. This is one of them, of course, such things are rarely involved in our development. Let me give you another commonly used scenario. In our distributed architecture, we often encounter read and write separation scenarios. During the writing process, you can use redis to publish subscriptions, so that the written values are published to each read program in a timely manner, ensuring the complete consistency of the data. For example, in a blog website, 100 fans subscribe to you. When you post a new article, you can push messages to your fans. In short, there are many scenes and need to be explored. .
Review how Java operates redis:
Redis is a cache database, which is also the structure of C/S, that is, the client and the server. Generally speaking, in Java, we usually use jedis (client) to operate redis (server). When operating, a connection must be established between the two. Just like a database link, in a relational database, we generally maintain a connection pool to achieve link reuse, so as to save time to establish and close connections. Therefore, in jedis, there is also a concept of jedispool (jedis connection pool), and we all use connections from the pool.
On code:
If you want to use jedis, you will first introduce dependencies
<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(); //Fetch a connection from the connection pool while (true) { String line = null; try { line = reader.readLine(); if (!"quit".equals(line)) { jedis.publish("mychannel", line); //Push a message from mychannel's channel} 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) { //Receive a message and call System.out.println(String.format("receive redis published message, channel %s, message %s", channel, message)); } @Override public void onSubscribe(String channel, int subscribedChannels) { //Unsubscribed to the channel will call System.out.println(String.format("subscribe redis channel success, channel %s, subscribedChannels %d", channel, subscribedChannels)); } @Override public void onUnsubscribe(String channel, int subscribedChannels) { //Unsubscribed will call System.out.println(String.format("unsubscribe redis channel, channel %s, subscribedChannels %d", channel, subscribedChannels)); }}Here, subscribers need to inherit JedisPubSub to rewrite its three methods. The purpose comment has been written, it is very simple.
We just define a subscriber here, and go to the subscription 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 jedis = null; try { jedis = jedisPool.getResource(); //Take out a connection jedis.subscribe(subscriber, channel); //Subscribe through the subscribe API, the 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 and run it. Enter a message on the keyboard and the subscriber will trigger 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); //Subscriber subThread.start(); Publisher publisher = new Publisher(jedisPool); //Publisher publisher.start(); }}See the print results
Attach the code address https://github.com/fangyong1421/redis
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.