Python implements the redis subscription and publishing function, pythonredis
Redis is a key-value storage system. Similar to Memcached, Memcached supports more storage value types, including string, list, set, and zset) and hash (hash type ). The subscription and publishing system can also be implemented. Let's take a look at how to use redis and python to subscribe and publish,
Import redisclass RedisSubscri (): def _ init _ (self, host): self. coon = redis. redis (host = "127.0.0.1") def publish (self, message, channel): # publish self. coon. publish (channel, message) def subscribe (self, channel): # subscribe pub = self. coon. pubsub () pub. subscribe (channel) pub. parse_response () return pub def unsubsceribe (self, channel): # unsubscribe to self. coon. pubsub (). unsubscribe (channel)
The core code is that it can be used after simple encapsulation.
Publication end redisd = RedisSubscri (host = '20180101. 0.0.1 ') while True: n = input ("Enter the channel you want to publish:") m = input ("Enter the message you want to publish:") redisd. publish (m, n)
Subscription end from dingyue import RedisSubscriif _ name __= = "_ main _": resad = RedisSubscri (host = '2017. 0.0.1 ') meaaag = resad. subscribe ('1') while True: print ('listener start') meaaage = meaaag. parse_response () print (meaaage [2]. decode ('utf-8') if meaaage [2]. decode ('utf-8') = '1': m = meaaag. unsubscribe ('fm9. 01 ') print (m) print ('subscription canceled successfully') break
Then let's run the above Code to see if the login and subscription functions can be implemented and the Unsubscription functions can be implemented.
Publisher:
Subscription end
We defined in the Code above. When the message is received as 1, we cancel the subscription,
After canceling the subscription, you cannot subscribe to system messages. Therefore, the output is None.
In this way, python and redis are used to implement the subscription and release function. In fact, redis can be used in many places. In-depth research will be introduced in subsequent articles.
1.1 drops, learning python, and recording the path to python.
I am using python.