一、安装与使用Redis
1)sudo apt-get update
2)sudo apt-get install redis-server
3)启动server
redis-server
4)启动client
redis-cli
5)存储数据
写法:set key value
示例:set name xiaoming
6)获取数据
写法:get key
示例:get name
7)订阅消息
写法:subscribe 主题
示例:subscribe chat
8)发布消息
写法:publish 主题 内容
示例:publish chat 123123
可开启多个窗口进行订阅,然后测试发布。
二、编程
1)安装redis库
pip3 install redis
打开pycharm新建工程
新建3个文件:publish.py 、subscribe.py 、helper.py
publish.py代码:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from helper import RedisHelper
obj = RedisHelper()
obj.publish('hello')
subscribe.py代码:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from helper import RedisHelper
obj = RedisHelper()
redis_sub = obj.subscribe()
while True:
msg= redis_sub.parse_response()
print (msg)
helper.py代码:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import redis
class RedisHelper(object):
def __init__(self):
self.__conn = redis.Redis(host='localhost',port=6379)
self.channel = 'monitor'
def publish(self,msg):
self.__conn.publish(self.channel,msg)
return True
def subscribe(self):
pub = self.__conn.pubsub()
pub.subscribe(self.channel)
pub.parse_response()
return pub
1)打开命令行窗口输入redis-server 启动服务。
2)运行subscribe.py程序
3)运行publish.py程序
运行结果如下: