Home > Java > javaTutorial > What is Redis publish and subscribe?

What is Redis publish and subscribe?

PHP中文网
Release: 2017-06-20 09:56:16
Original
1638 people have browsed it

I thought of using the Redis subscription publishing model to solve the push problem~.

For the conceptual description, I still need to mention it more or less:

什么是Redis发布订阅?Redis发布订阅是一种消息通信模式,发送者通过通道A发送消息message,订阅过通道A的客户端就可以接收到消息message。嗯度娘上面的解释要比我所说的好多了,而我所理解的就是:所谓的订阅发布模式,其实和我们看电视,听广播差不多,在我们没有调台(换频道)的时候,那个频道也是在传递消息的(发布)。我们换到那个频道上(订阅)就能接收到消息了。是的,虽然可能有些不恰当~
Copy after login

Explanation

本文中示例采用了三个客户端,以“品”字形排列,由上至下,由左至右分别为客户端1(c1),客户端2(c2),客户端3(c3).特此说明。
Copy after login

Redis subscription and publishing commands

First of all, declare, Regarding the construction of the Redis server, please check the relevant information by yourself to build the environment

I heard that there are only 6 simple commands for publishing and subscribing in Redis. That is:

  • PSUBSCRIBE pattern [pattern ...]

  • Subscribe to one or more channels that match the pattern format

  • PUBLISH channel message

  • Publish message to chanel

  • PUBSUB subcommand [argument [argument ...]]

  • View subscription and publishing system status

  • PUNSUBSCRIBE [pattern [pattern ...]]

  • Unsubscribe from all channels that match the format

  • SUBSCRIBE channel [channel ...]

  • Subscribe to one or more channels

  • UNSUBSCRIBE [channel [channel ...]]

  • Unsubscribe channel


##Example 1 - SUBSCRIBE

After connecting to redis, type the command

SUBSCRIBE study
Copy after login
to subscribe to a channel named study.

The study channel will send a message next. ~~


Example 2 - PUBLISH

Open another client. I use the top one in the glyph layout as the publisher, type

PUBLISH study "message1-go go go"
Copy after login
It can be seen that when client 1 publishes a message in the study channel, client 2 (subscribed to the study channel) can receive the message published by c1, while client 3 cannot receive the message sent by c1 because it has not subscribed to the study channel. information.


Example 3 - PSUBSCRIBE

Now, follow the blogger’s left hand and right hand in slow motion. Type

PSUBSCRIBE study*
Copy after login
OK in c3, now type

PUBLISH study "message2"
Copy after login
in c1. The above result picture:

c3 adopts the form of wildcard, and the study channel is also successfully subscribed. .

Next, continue typing the command in c1:

PUBLISH study:java "I hate java forever"
Copy after login
You can see that using psubscribe not only subscribes to the study channel, but also subscribes to the channel headed by study.


Example 4 - PUBSUB

Type pubsub channel in c1, you can get:

127.0.0.1:6379> PUBSUB channels

1) "study"
Copy after login
means the currently active channel.


Jedis implements the subscription publisher mode

好了,上面通过命令行熟悉了一下Redis中有关订阅发布者模式的相关命令。下面我们要将redis的订阅与发布者嵌入到项目中。

首先,我们使用jedis先订阅一个名为:study的频道
Copy after login
Then we first publish the message from the command line:

After that, we use jedis to publish the message in the project :

We can have normal communication~Oh yeah~


Core code:

PublishMessage.java is used to start a thread to publish messages

private Logger logger = LoggerFactory.getLogger(PublishMessage.class);

@Resource
private JedisCluster jedisCluster;

/**
 * 发布消息
 *
 * @param channel 频道
 * @param message 信息
 */
public void sendMessage(final String channel, final String message) {
    Thread thread = new Thread(() -> {
        Long publish = jedisCluster.publish(channel, message);
        logger.info("服务器在: {} 频道发布消息{} - {}", channel, message, publish);
    });
    logger.info("发布线程启动:");
    thread.setName("publishThread");
    thread.start();
}
Copy after login
ChatSubscribe.java is used to handle subscription-related events, inherited from JedisPubSub

private Logger logger = LoggerFactory.getLogger(ChatSubscribe.class);

// 取得订阅的消息后的处理
@Override
public void onMessage(String channel, String message) {
    logger.info("订阅成功,接收到的消息为:频道-{},消息-{}", channel, message);
    RedisString.message = message;
}

// 取得按表达式的方式订阅的消息后的处理
@Override
public void onPMessage(String pattern, String channel, String message) {
    System.out.println("-----取得按表达式的方式订阅的消息后的处理-----");
    System.out.println(pattern + "=" + channel + "=" + message);
}

// 初始化按表达式的方式订阅时候的处理
@Override
public void onPSubscribe(String pattern, int subscribedChannels) {
    System.out.println("-----初始化按表达式的方式订阅时候的处理-----");
    System.out.println(pattern + "=" + subscribedChannels);
}

// 取消按表达式的方式订阅时候的处理
@Override
public void onPUnsubscribe(String pattern, int subscribedChannels) {
    System.out.println("-----取消按表达式的方式订阅时候的处理-----");
    System.out.println(pattern + "=" + subscribedChannels);
}

@Override
public void onPong(String pattern) {
    super.onPong(pattern);
}

// 初始化订阅时候的处理
@Override
public void onSubscribe(String channel, int subscribedChannels) {
    logger.info("初始化订阅信息:频道-{},订阅频道-{}", channel, subscribedChannels);
}

// 取消订阅时候的处理
@Override
public void onUnsubscribe(String channel, int subscribedChannels) {
    logger.info("已取消订阅频道{}", channel);
}
Copy after login
SubScribeMessage.java subscribing to channels, canceling channels and other action classes

private Logger logger = LoggerFactory.getLogger(SubScribeMessage.class);

private ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

@Resource
private JedisCluster jedisCluster;
/**
     * 订阅频道
     *
     * @param channel          频道
     * @param roomSubListerner
     */
    public void subscribeChannel(final String channel, final ChatSubscribe roomSubListerner) {

        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                jedisCluster.subscribe(roomSubListerner, channel);
            }
        });
    }

jedisCluster是否封装工具类,取自各位看官,核心代码已给出,请各位看官根据自身业务与逻辑,自行更改与优化代码。

本次示例程序采用tomcat 9.0 + spring + springmvc

使用了诸如:@RestController,@GetMapping等相关注解,便于开发,有兴趣可自行查阅spring相关资料。
Copy after login

The above is the detailed content of What is Redis publish and subscribe?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template