1+ #!/usr/bin/env python
2+ # encoding: utf-8
3+
4+ """
5+ @author: zhanghe
6+ @software: PyCharm
7+ @file: redis_pub_sub.py
8+ @time: 2017/2/14 下午11:03
9+ """
10+
11+
12+ import sys
13+ import redis
14+ import json
15+
16+
17+ class RedisPubSub (object ):
18+ """
19+ Pub/Sub
20+ """
21+ def __init__ (self , name , namespace = 'queue' , ** redis_kwargs ):
22+ """The default connection parameters are: host='localhost', port=6379, db=0"""
23+ self .__db = redis .Redis (** redis_kwargs )
24+ self .key = '%s:%s' % (namespace , name )
25+
26+ def pub (self , k , v ):
27+ """
28+ Pub
29+ :param k:
30+ :param v:
31+ :return:
32+ """
33+ ch = '%s:%s' % (self .key , k )
34+ self .__db .publish (ch , v )
35+
36+ def sub (self , k ):
37+ """
38+ Sub
39+ :param k:
40+ :return:
41+ """
42+ ps = self .__db .pubsub ()
43+ ch = '%s:%s' % (self .key , k )
44+ ps .subscribe (ch )
45+ for item in ps .listen ():
46+ # {'pattern': None, 'type': 'subscribe', 'channel': 'queue:test:hh', 'data': 1L}
47+ # yield item
48+ yield item .get ('data' )
49+
50+ def sub_not_loop (self , k ):
51+ """
52+ Sub 非无限循环,取到结果即退出
53+ :param k:
54+ :return:
55+ """
56+ ps = self .__db .pubsub ()
57+ ch = '%s:%s' % (self .key , k )
58+ ps .subscribe (ch )
59+ for item in ps .listen ():
60+ if item ['type' ] == 'message' :
61+ return item .get ('data' )
62+
63+
64+ def test_pub ():
65+ q = RedisPubSub ('test' )
66+ q .pub ('hh' , '123' )
67+
68+
69+ def test_sub ():
70+ q = RedisPubSub ('test' )
71+ r = q .sub ('hh' )
72+ for i in r :
73+ print i
74+
75+
76+ def test_sub_not_loop ():
77+ q = RedisPubSub ('test' )
78+ r = q .sub_not_loop ('hh' )
79+ print r
80+
81+
82+ def run ():
83+ # print sys.argv
84+ try :
85+ if len (sys .argv ) > 1 :
86+ fun_name = eval (sys .argv [1 ])
87+ fun_name ()
88+ else :
89+ print '缺失参数'
90+ except NameError , e :
91+ print e
92+ print '未定义的方法[%s]' % sys .argv [1 ]
93+
94+
95+ if __name__ == '__main__' :
96+ run ()
97+
98+
99+ """
100+ 测试一般模式
101+ 终端一:
102+ ✗ python redis_pub_sub.py test_sub
103+ 终端二:
104+ ✗ python redis_pub_sub.py test_pub
105+
106+
107+ 测试非无限循环模式
108+ 终端一:
109+ ✗ python redis_pub_sub.py test_sub_not_loop
110+ 终端二:
111+ ✗ python redis_pub_sub.py test_pub
112+ """
0 commit comments