一、安装与使用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

redis项目实例demo redis编程实例_Redis


7)订阅消息

写法:subscribe 主题

示例:subscribe chat

redis项目实例demo redis编程实例_python_02


8)发布消息

写法:publish 主题 内容

示例:publish chat 123123

redis项目实例demo redis编程实例_redis_03


可开启多个窗口进行订阅,然后测试发布。

二、编程

1)安装redis库

pip3 install redis

打开pycharm新建工程

redis项目实例demo redis编程实例_Redis_04


新建3个文件:publish.py 、subscribe.py 、helper.py

redis项目实例demo redis编程实例_redis项目实例demo_05

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程序

运行结果如下:

redis项目实例demo redis编程实例_redis_06