python和redis之间的交互
2018-07-17 23:06
459 查看
python和redis之间的交互
一. redis模块
安装模块:
pip3 install redis
连接方式:
r = redis.Redis(host='localhost',port=6379)
连接池:为了节约资源,减少多次连接带来的消耗。
pool=redis.ConnectionPool(host='localhost',port=6379,decode_responses=True)
二.redis操作
常规操作:
import redis r = redis.Redis(host='localhost',port=6379) r.set('foo','bar') print(r.get('foo'))
连接池:
import redis pool = redis.ConnectionPool(host='localhost',port=6379,decode_responses=True) # 默认设置的值和取得的值都是bytes类型,如果想改为str类型,可以添加decode_responses=True r1 = redis.Redis(connection_pool=pool) r2 = redis.Redis(connection_pool=pool) r1.set('name','jack') print(r1.get('name')) r2.set('age',18) print(r2.get('age')) print(r1.client_list()) print(r2.client_list())
管道:
import redis,time r = redis.Redis(host='localhost',port=6379,decode_responses=True) pipe = r.pipeline(transaction=True) pipe.set('name1','Alin') pipe.set('name2','Lnda') pipe.set('name3','Tony') time.sleep(5) pipe.execute() print(r.mget('name1','name2','name3'))
事务:python可以使用管道来代替事务
import redis,time import redis.exceptions r = redis.Redis(host='localhost',port=6379,decode_responses=True) pipe = r.pipeline() print(r.get('name1')) try: pipe.multi() pipe.set('age1',22) pipe.set('age2',23) pipe.set('age3',24) time.sleep(5) pipe.execute() print(r.mget('age1','age2','age3')) except redis.exceptions.WatchError as e: print('Error')
订阅和发布:
发布方:
import redis r = redis.Redis(host='localhost',port=6379,decode_responses=True) while True: msg = input('echo>>:') if len(msg) == 0: continue elif msg == 'quit': r.publish('cctv1',msg) break else: r.publish('cctv1',msg)
订阅方:
import redis r = redis.Redis(host='localhost',port=6379,decode_responses=True) chan = r.pubsub() #返回一个发布订阅对象 msg_reciver = chan.subscribe('cctv1') #订阅 msg = chan.parse_response() # 返回一个确认 print(msg) print('订阅成功,开始接收...') while True: msg = chan.parse_response() #接收消息 if msg[2] == 'quit': #格式:类型,频道,消息 break else: print('>>:', msg[2])
相关文章推荐
- 3.Redis与python交互
- (架构设计)观察者模式+redis队列实现不同项目之间数据的交互
- Redis数据库和Python的交互
- python基础之类和对象、对象之间的交互、类名称空间与对象/实例名称空间
- redis与python交互
- redis python交互和实际例子
- python与redis交互
- Redis 与Python 交互
- java python之间数据交互(使用jython)
- redis数据库和python的交互(完整版)
- redis和Python交互
- 用python和redis交互操作
- 15.18数据库(18):Python与Redis的交互
- 利用Python的paramiko+scpclient实现高效和ssh服务器交互
- SWIG 和 Python——c/c++与脚本交互
- python redis
- 关于mongodb ,redis,memcache之间见不乱理还乱的关系和作用
- 智能家居软硬件结合之手机控制电器(手机与Python后台交互)
- redhat下使用mysql,python,redis,httpsqs,shell脚本开机自启动的一些问题与解决
- Python raw_input()和input() 函数 读取交互输入