天天看點

python實作 redis訂閱與釋出

  訂閱者可以訂閱一個或多個頻道,釋出者向一個頻道發送消息後,所有訂閱這個頻道的訂閱者都将收到消息,而釋出者也将收到一個數值,這個數值是收到消息的訂閱者的數量。訂閱者隻能收到自它開始訂閱後釋出者所釋出的消息,之前釋出的消息呢,就不可能收到了。

                                           多的不說看代碼!!!

面向過程的方法

#!/usr/bin/python

#coding:utf-8

#伺服器端

import redis  

r = redis.Redis(host='127.0.0.1',port='6379') #連接配接redis

p = r.pubsub()        #開啟訂閱

p.subscribe('6379')  #接收訂閱的資料,訂閱的頻道 

for item in p.listen():  #讀取接收的資料

    print item 

    if item['type'] == 'message': #判斷資料是否是使用者釋出的資料   

        data = item['data']      #取出使用者要釋出的資料

        print data   #列印要釋出的資料

        if item['data'] == 'Q' or item['data'] == 'q':    

            break;       #退出程式

p.unsubscribe('6379') #關閉頻道  

print '取消訂閱'

#用戶端

#!/usr/bin/py

r = redis.Redis(host='127.0.0.1',port=6379) #連接配接redis

while True:  

    my_input = raw_input("請輸入釋出内容:") #輸入釋出的内容  

    r.publish('6379', my_input) #發送到的頻道,釋出的内容   

    if my_input == 'Q' or my_input == 'q':       #判斷使用者是否要退出程式

        print '停止釋出'  

        break; 

面向對象的方法

import redis

class server(object):

    def __init__(self,ip='127.0.0.1',port=6379,sub='A'):

        self.ip = ip

        self.port = port

        self.connect = redis.Redis(host=self.ip,port=self.port)   #連接配接redis

        self.sub = sub  #監聽頻道

    def se(self):

        spub = self.connect.pubsub() #打開訂閱

        spub.subscribe(self.sub) #開始監聽

        spub.listen() #使用者釋出的資料

        return spub

x = server()

p = x.se()

for item in p.listen():     #列印接收到的資料

    print item

class client(object):

    def __init__(self,ip='127.0.0.1',port=6379,pub='A'):

        self.connect = redis.Redis(host=self.ip,port=self.port)

        self.pub = pub         #連接配接的頻道

    def cl(self,content):

        self.connect.publish(self.pub,content) #頻道,發送的資料

x = client()

while True:

    my_input = raw_input('請輸入釋出内容:')     #釋出的資料

    x.cl(my_input)

        個人比較喜歡第二種方法,也推薦各位朋友使用第二種方法,第二種方法中我沒有對接收到的資料進行過多的處理,如果各位朋友喜歡可以拿去自行修改

本文轉自  紅塵世間  51CTO部落格,原文連結:http://blog.51cto.com/hongchen99/1909790