Wonderjar's Blog

Python直接使用Redis作为Broker的例子

2018-07-31

记录一下

Docker安装redis

mapping port,
docker run -p 6379:6379 –name some-redis -d redis

Python code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
r = redis.StrictRedis(...)
p = r.pubsub()

def my_handler(message):
print 'MY HANDLER: ', message['data']

# subscribe
p.subscribe('my-first-channel', 'my-second-channel', ...)
p.psubscribe('my-*', ...)
p.subscribe(**{'my-channel': my_handler})

# publish
r.publish('my-channel', 'hello python')

# 需要自己处理event loop
while True:
message = p.get_message()
if message:
# do something with the message
time.sleep(0.001) # be nice to the system :)

# 另一种办法启动event loop,这种方法必须所有subscribe都要注册handler
p.subscribe(**{'my-channel': my_handler})
thread = p.run_in_thread(sleep_time=0.001)
# the event loop is now running in the background processing messages
# when it's time to shut it down...
thread.stop()

记录一些redis-cli的命令

select DB
PUBLISH CHANNEL MESSAGE
keys
keys TEST

set KEY VALUE
get KEY

Tags: Python