Home Java javaTutorial What is Redis publish and subscribe?

What is Redis publish and subscribe?

Jun 20, 2017 am 09:56 AM
jedis redis release accomplish subscription

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solution to 0x80242008 error when installing Windows 11 10.0.22000.100 Solution to 0x80242008 error when installing Windows 11 10.0.22000.100 May 08, 2024 pm 03:50 PM

1. Start the [Start] menu, enter [cmd], right-click [Command Prompt], and select Run as [Administrator]. 2. Enter the following commands in sequence (copy and paste carefully): SCconfigwuauservstart=auto, press Enter SCconfigbitsstart=auto, press Enter SCconfigcryptsvcstart=auto, press Enter SCconfigtrustedinstallerstart=auto, press Enter SCconfigwuauservtype=share, press Enter netstopwuauserv , press enter netstopcryptS

Golang API caching strategy and optimization Golang API caching strategy and optimization May 07, 2024 pm 02:12 PM

The caching strategy in GolangAPI can improve performance and reduce server load. Commonly used strategies are: LRU, LFU, FIFO and TTL. Optimization techniques include selecting appropriate cache storage, hierarchical caching, invalidation management, and monitoring and tuning. In the practical case, the LRU cache is used to optimize the API for obtaining user information from the database. The data can be quickly retrieved from the cache. Otherwise, the cache can be updated after obtaining it from the database.

Caching mechanism and application practice in PHP development Caching mechanism and application practice in PHP development May 09, 2024 pm 01:30 PM

In PHP development, the caching mechanism improves performance by temporarily storing frequently accessed data in memory or disk, thereby reducing the number of database accesses. Cache types mainly include memory, file and database cache. Caching can be implemented in PHP using built-in functions or third-party libraries, such as cache_get() and Memcache. Common practical applications include caching database query results to optimize query performance and caching page output to speed up rendering. The caching mechanism effectively improves website response speed, enhances user experience and reduces server load.

How to upgrade Win11 English 21996 to Simplified Chinese 22000_How to upgrade Win11 English 21996 to Simplified Chinese 22000 How to upgrade Win11 English 21996 to Simplified Chinese 22000_How to upgrade Win11 English 21996 to Simplified Chinese 22000 May 08, 2024 pm 05:10 PM

First you need to set the system language to Simplified Chinese display and restart. Of course, if you have changed the display language to Simplified Chinese before, you can just skip this step. Next, start operating the registry, regedit.exe, directly navigate to HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlNlsLanguage in the left navigation bar or the upper address bar, and then modify the InstallLanguage key value and Default key value to 0804 (if you want to change it to English en-us, you need First set the system display language to en-us, restart the system and then change everything to 0409) You must restart the system at this point.

How to use Redis cache in PHP array pagination? How to use Redis cache in PHP array pagination? May 01, 2024 am 10:48 AM

Using Redis cache can greatly optimize the performance of PHP array paging. This can be achieved through the following steps: Install the Redis client. Connect to the Redis server. Create cache data and store each page of data into a Redis hash with the key "page:{page_number}". Get data from cache and avoid expensive operations on large arrays.

How to find the update file downloaded by Win11_Share the location of the update file downloaded by Win11 How to find the update file downloaded by Win11_Share the location of the update file downloaded by Win11 May 08, 2024 am 10:34 AM

1. First, double-click the [This PC] icon on the desktop to open it. 2. Then double-click the left mouse button to enter [C drive]. System files will generally be automatically stored in C drive. 3. Then find the [windows] folder in the C drive and double-click to enter. 4. After entering the [windows] folder, find the [SoftwareDistribution] folder. 5. After entering, find the [download] folder, which contains all win11 download and update files. 6. If we want to delete these files, just delete them directly in this folder.

PHP Redis caching applications and best practices PHP Redis caching applications and best practices May 04, 2024 am 08:33 AM

Redis is a high-performance key-value cache. The PHPRedis extension provides an API to interact with the Redis server. Use the following steps to connect to Redis, store and retrieve data: Connect: Use the Redis classes to connect to the server. Storage: Use the set method to set key-value pairs. Retrieval: Use the get method to obtain the value of the key.

Meizu's new phone exposed, equipped with a 6000mAh large battery, Meizu 22 will be released later Meizu's new phone exposed, equipped with a 6000mAh large battery, Meizu 22 will be released later Aug 07, 2024 pm 07:02 PM

On August 6, CNMO noticed that Meizu’s new phone was exposed again. According to information provided by the source, Meizu is preparing a mid-range model, which is expected to be equipped with a 6000mAh ultra-large capacity battery. There is no news about the Meizu 22 series for the time being. It is expected to be equipped with Qualcomm Snapdragon 8Gen4 mobile platform, and the release time may be later. Referring to previous new Meizu phones, CNMO believes that the Meizu 22 series may be released in the first quarter of 2025. 1. Meizu’s new phone has passed the national quality certification and its model is M431Q. This machine is positioned as an entry-level model and only supports 10W charging. The price is expected to be around 1,000 yuan. The phone is suspected to be a product of Meizu sub-brand Meizu. The M431Q was discovered in the database in May this year, along with several other models. This time passed the national quality

See all articles