Python编程:redis缓存数据库
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
- 1
简单连接
import redis
r = redis.Redis(host="127.0.0.1", port=6379)
r.set("foo", "xxx")
print(r.get("foo")) # b'xxx'
- 1
- 2
- 3
- 4
- 5
- 6
- 7
url链接
redis://username[:password]@host:port/db # TCP连接
- 1
- 2
连接池
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"))
- 1
- 2
- 3
- 4
- 5
- 6
- 7
管道
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"))
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
发布者和订阅者
# 封装的公共类
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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
# 发布者
import redis_helper
obj = redis_helper.RedisHelper()
obj.public('hello')
print("发布成功")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
# 订阅者
import redis_helper
obj = redis_helper.RedisHelper()
redis_sub = obj.subscribe()
print("开始订阅")
while True: msg = redis_sub.parse_response() print(msg)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
参考文章:
redis-py
https://github.com/andymccurdy/redis-py/Redis 命令参考
http://doc.redisfans.com/《Redis 教程-菜鸟教程》
http://www.runoob.com/redis/redis-tutorial.html《Python之路【第九篇】:Python操作Redis》
http://www.cnblogs.com/wupeiqi/articles/5132791.html《python 之路,Day12 - redis缓存数据库》
http://www.cnblogs.com/alex3714/articles/6217453.html
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/79190790
- 点赞
- 收藏
- 关注作者
评论(0)