Redis from getting started to giving up: publishing and subscribing

1 Introduction

Redis is a fast, open source in-memory database that supports a variety of data structures, such as strings, hashes, lists, sets, ordered sets, etc. In addition to basic data storage and retrieval functions, Redis also provides many advanced functions, one of which is publish and subscribe (Pub/Sub).

Publish-subscribe is a messaging pattern that allows the publisher of a message (publisher) to send messages to multiple subscribers (subscribers) without knowing that the subscribers exist. This pattern is very useful in many applications, such as real-time notifications, event handling, chat applications, etc.

2. How to use publish and subscribe

2.1. Subscribe to channels

To subscribe to a channel, you first need to use  SUBSCRIBE the command. Suppose we have a channel named  notifications, here is the sample code to subscribe to the channel:

[root@ds-huangshan-01 src]# ./redis-cli 
127.0.0.1:6379> SUBSCRIBE notifications
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "notifications"
3) (integer) 1      # 返回值为当前已订阅的频道数量

After executing the above command, the current client will enter the subscription state, and it will continue to wait for  notifications messages from the channel. If the channel does not exist, the client will block until a message is published to the channel.

2.2. Release news

To publish a message to a specified channel, use  PUBLISH the command. notifications Here is sample code for posting a message to  a channel:

Publisher (publish message):

[root@ds-huangshan-01 src]# ./redis-cli 
127.0.0.1:6379> publish notifications "hello world!"
(integer) 1

After executing the above command, all  notifications clients that have subscribed to the channel will receive the message "hello world!".

"message"
"notifications"
"hello world!"

2.3. Cancel subscription

If a client no longer needs to receive messages from a specific channel, it can use  UNSUBSCRIBE the command to unsubscribe. If no channel name is specified, the client will unsubscribe from all channels.

UNSUBSCRIBE notifications

2.4. Pattern subscription

In addition to ordinary channel subscriptions, Redis also supports pattern subscriptions (Pattern Subscriptions). Pattern subscriptions allow clients to subscribe to channels that satisfy a specific pattern.

For example, let's say we have multiple channel names starting with "notifications:" followed by different categories (such as "notifications:news", "notifications:sports", etc.). To subscribe to all channels starting with "notifications:" you can use the following command:

PSUBSCRIBE notifications:*

2.5. Cancel mode subscription

Use the command to cancel a mode subscription  PUNSUBSCRIBE , and its usage is similar to canceling a normal channel subscription.

PUNSUBSCRIBE notifications:*

There are two points to note about the subscription command:

  1. The client enters the subscription state after executing the subscription command and can only receive four commands: subscribe, psubscribe, unsubscribe, and punsubscribe.
  2. A newly opened subscription client cannot receive previous messages from the channel because Redis does not persist published messages.

3. Use cases (pseudocode)

Message notification:  In a web application, you can use the publish and subscribe function to send real-time notifications to all online users, such as new messages, new orders, etc.

Redis publisher code:

import redis.clients.jedis.Jedis;

public class RedisPublisher {

    public static void main(String[] args) {
        // 连接到Redis服务器
        Jedis jedis = new Jedis("localhost");

        // 发布消息到频道
        jedis.publish("notifications", "Hello, world!");

        // 关闭连接
        jedis.close();
    }
}

// Redis subscriber code

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

public class RedisSubscriber extends JedisPubSub {

    @Override
    public void onMessage(String channel, String message) {
        System.out.println("Received message: " + message + " from channel: " + channel);
        // 在这里可以实现发送通知给在线用户的逻辑
    }

    public static void main(String[] args) {
        // 连接到Redis服务器
        Jedis jedis = new Jedis("localhost");

        // 创建订阅者实例
        RedisSubscriber subscriber = new RedisSubscriber();

        // 订阅频道
        jedis.subscribe(subscriber, "notifications");

        // 关闭连接
        jedis.close();
    }
}

4. The difference between Redis publish and subscribe and ActiveMQ and RocketMQ

Redis publish and subscribe, ActiveMQ and RocketMQ are different types of messaging systems. They have the following differences:

  1. Message Queuing Pattern vs. Publish-Subscribe Pattern :

    • ActiveMQ and RocketMQ are message queue systems and they follow the message queue pattern. A message queue sends messages to one or more consumers, and each message can only be processed by one consumer.
    • Redis publish and subscribe is a publisher-subscriber model, in which a message can be broadcast to multiple subscribers.
  2. Durability :

    • ActiveMQ and RocketMQ usually support message persistence, which ensures that messages are not lost even if the consumer goes offline.
    • Redis publish and subscribe does not support persistence by default. Once a message is sent, if no subscriber receives it, the message will be lost;
  3. Features :

    • ActiveMQ and RocketMQ provide rich features, such as message retry, message order guarantee, delayed message, etc.
    • Redis's publish and subscribe is relatively simple and is mainly used for real-time notifications and the publication and subscription of simple messages.
  4. Distributed features :

    • Both ActiveMQ and RocketMQ are designed for distributed environments and support clustering and load balancing.
    • Redis can be used in a distributed environment, but its publish and subscribe functions are relatively simple and are not as flexible as ActiveMQ and RocketMQ in complex distributed scenarios.

Overall, if you need a feature-rich messaging system that focuses on the message queue model, you can choose ActiveMQ or RocketMQ. And if you only need simple publish and subscribe functions, Redis publish and subscribe is a good choice.

 

Guess you like

Origin blog.csdn.net/2301_78834737/article/details/132004630