python-redis
1、使用python的redis模块进行连接
#!/usr/bin/env python # _*_ coding:utf-8 _*_ import redis redisDB = redis.Redis(host='127.0.0.1',port=6379,db=0) keys = redisDB.keys()#获取所有的键 print keys
2、使用redis的连接池连接
#!/usr/bin/env python # _*_ coding:utf-8 _*_ import redis redisPool = redis.ConnectionPool(host='127.0.0.1',port=6379) redisDB = redis.Redis(connection_pool=redisPool) keys = redisDB.keys()#获取所有的keys print keys
3、管道(redis每次执行完毕就会断开连接,使用管道可以一次执行多个指令)
#!/usr/bin/env python # _*_ coding:utf-8 _*_ import redis redisPool = redis.ConnectionPool(host='127.0.0.1',port=6379) redisDB = redis.Redis(connection_pool=redisPool) pipe = redisDB.pipeline(transaction=True) redisDB.set('name','zs') redisDB.set('sex','male') pipe.execute()
4、发布和订阅
1、定义帮助类
#!/usr/bin/env python # _*_ coding:utf-8 _*_ import redis class redisHelper: #定义类,类中定义发布和订阅方法 def __init__(self,channel=None): self.conn = redis.Redis(host='127.0.0.1',port=6379) self.channel = channel def publish(self,msg): #定义发布方法 if self.channel and msg: self.conn.publish(self.channel,msg) return True else: return False def subscribe(self): #定义订阅方法 pub = self.conn.pubsub() if self.channel: pub.subscribe(self.channel) return pub else: return False
2、先订阅频道
#!/usr/bin/env python # _*_ coding:utf-8 _*_ from demo.redis_study.redishelp import redisHelper # 订阅 redis_obj = redisHelper('mychannle') sub_obj = redis_obj.subscribe() while True: msg = sub_obj.parse_response() #获取发布的结果 print msg
3、在指定频道发布信息
#!/usr/bin/env python # _*_ coding:utf-8 _*_ from demo.redis_study.redishelp import redisHelper # 发布 redis_obj = redisHelper('mychannle') redis_obj.publish('hello')
刷初步设计被拆包时间戳