What is Redis publish and subscribe?
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。嗯度娘上面的解释要比我所说的好多了,而我所理解的就是:所谓的订阅发布模式,其实和我们看电视,听广播差不多,在我们没有调台(换频道)的时候,那个频道也是在传递消息的(发布)。我们换到那个频道上(订阅)就能接收到消息了。是的,虽然可能有些不恰当~
Explanation
本文中示例采用了三个客户端,以“品”字形排列,由上至下,由左至右分别为客户端1(c1),客户端2(c2),客户端3(c3).特此说明。
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
Example 2 - PUBLISHOpen another client. I use the top one in the glyph layout as the publisher, type
PUBLISH study "message1-go go go"
Example 3 - PSUBSCRIBENow, follow the blogger’s left hand and right hand in slow motion. Type
PSUBSCRIBE study*
PUBLISH study "message2"
PUBLISH study:java "I hate java forever"
Example 4 - PUBSUBType pubsub channel in c1, you can get:
127.0.0.1:6379> PUBSUB channels 1) "study"
Jedis implements the subscription publisher mode
好了,上面通过命令行熟悉了一下Redis中有关订阅发布者模式的相关命令。下面我们要将redis的订阅与发布者嵌入到项目中。 首先,我们使用jedis先订阅一个名为:study的频道
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(); }
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); }
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相关资料。
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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.

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.

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.

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.

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.

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.

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
