First introduce the pub/sub function of redis:
The Pub/Sub feature, which stands for Publish and Subscribe, refers to the functionality of publishing and subscribing.. In event-based systems, Pub/Sub is currently a widely used communication model. It uses events as the basic communication mechanism to provide a loosely coupled interaction model required by large-scale systems: subscribers (such as clients) subscribe to events. The method expresses an event or a type of event that it is interested in receiving; the publisher (such as the server) can notify relevant subscribers at any time of events that the subscriber is interested in.
In lay terms, it means that my sub-side (subscriber) is always listening. Once the pub-side (publisher) publishes a message, then I will receive it. For example, the publisher first:
#coding:utf-8 import time import redis number_list = ['300033', '300032', '300031', '300030'] signal = ['1', '-1', '1', '-1'] rc = redis.StrictRedis(host='***', port='6379', db=3, password='********') for i in range(len(number_list)): value_new = str(number_list[i]) + ' ' + str(signal[i]) rc.publish("liao", value_new) #发布消息到liao
Then let’s take a look at the subscribers:
#coding:utf-8 import time import redis rc = redis.StrictRedis(host='****', port='6379', db=3, password='******') ps = rc.pubsub() ps.subscribe('liao') #从liao订阅消息 for item in ps.listen(): #监听状态:有消息发布了就拿过来 if item['type'] == 'message': print item['channel'] print item['data']
Regarding the data structure, that is, item, it is similar to: {'pattern': None, 'type': 'message', 'channel' : 'liao', 'data': '300033 1'}, so you can use the channel to determine which queue the message belongs to. (When running the program, run the subscriber first, and then run the publisher program)
To summarize, there are two main points:
The first is the connection method. There are three ways to use python to connect to redis: ① Use the Redis class in the library (or the StrictRedis class, which is almost the same); ② Use the ConnectionPool connection pool (which can maintain long connections); ③ Use the Sentinel class (if there are multiple redis clusters, The program will choose a suitable connection itself).
The second is the subscription method. The pubsub method in the StrictRedis class is used here. The way to subscribe to redis messages is to use the subscribe or psubscribe method, which starts after the connection is successful. Where subscribe is to subscribe to one channel, psubscribe can subscribe to multiple channels (when written like this, the channel as a parameter should be a list). Then you can start monitoring.
The above is the detailed content of How to implement Redis subscription and publishing using the sub-pub mechanism in python. For more information, please follow other related articles on the PHP Chinese website!