订阅专栏
broker缓存:
- mongodb 存硬盘
- redis 默认存内存,配置可存硬盘
- memcache 只能存内存
redis介绍
REmote DIctionary Server(Redis)
redis官网:https://redis.io/
redis数据类型:
- String 操作 set get
- Hash 操作 hset hget
- List 操作 lpush lrange
- Set 操作 sadd smembers
- Sort Set 操作
安装
windows安装下载:
https://github.com/MicrosoftArchive/redis/releases
启动服务:
切换目录到 C:\redis 运行 redis-server.exe redis.windows.conf
连接服务:
切换到redis目录下运行 redis-cli.exe -h 127.0.0.1 -p 6379
设置键值对 set myKey abc
取出键值对 get myKey
安装第三方库
pip install redis
简单连接
import redis r = redis.Redis(host="127.0.0.1", port=6379) r.set("foo", "xxx") print(r.get("foo")) # b'xxx'
url链接
redis://username[:password]@host:port/db # TCP连接
连接池
import redis pool = redis.ConnectionPool(host="127.0.0.1", port=6379) r = redis.Redis(connection_pool=pool) r.set("cat", "Tom") print(r.get("cat"))
管道
import redis pool = redis.ConnectionPool(host="127.0.0.1", port=6379) r = redis.Redis(connection_pool=pool) pipe=r.pipeline(transaction=True) pipe.set("key1", "value1") pipe.set("key2", "value2") pipe.execute() # 一起执行 print(r.get("key1"))
发布者和订阅者
# 封装的公共类
import redis class RedisHelper: def __init__(self): self.__conn = redis.Redis(host='127.0.0.1') self.chan_sub = 'fm104.5' self.chan_pub = 'fm104.5' def public(self, msg): self.__conn.publish(self.chan_pub, msg) return True def subscribe(self): pub = self.__conn.pubsub() pub.subscribe(self.chan_sub) pub.parse_response() return pub
# 发布者
import redis_helper obj = redis_helper.RedisHelper() obj.public('hello') print("发布成功")
# 订阅者
import redis_helper obj = redis_helper.RedisHelper() redis_sub = obj.subscribe() print("开始订阅") while True: msg = redis_sub.parse_response() print(msg)
参考文章:
redis-py
https://github.com/andymccurdy/redis-py/
Redis 命令参考
《Redis 教程-菜鸟教程》
http://www.runoob.com/redis/redis-tutorial.html
《Python之路【第九篇】:Python操作Redis》
http://www.cnblogs.com/wupeiqi/articles/5132791.html
《python 之路,Day12 - redis缓存数据库》