python redis使用心得
发布与订阅
连接池代码 redis_conn.py
import redis REDIS_CONN = { 'HOST': '192.168.1.11', 'PORT': '6378', 'DB': '1', 'CHANNEL': 'alarm', 'PASSWORD': '123456', } def redis_conn(): try: pool = redis.ConnectionPool(host=REDIS_CONN['HOST'], db=REDIS_CONN['DB'], port=REDIS_CONN['PORT']) r = redis.Redis(connection_pool=pool, password=REDIS_CONN['PASSWORD']) return r except Exception as err: print err
发布端代码
import json redis_publish_data = { "id": "", "content": "", } redis_publish_data['host_id'] = 123 redis_publish_data['content'] = "内容" redis_publish_data = json.dumps(redis_publish_data) REDIS_OBJ = redis_conn() REDIS_OBJ.publish(REDIS_CONN['CHANNEL'], redis_publish_data)
订阅端代码
import json REDIS_OBJ = redis_conn() def redis_subscribe(): p = REDIS_OBJ.pubsub() p.subscribe(REDIS_CONN['CHANNEL']) while True: for item in p.listen(): if item['type'] == 'message': # print item['channel'], item['data'], type(item['data']) data = json.loads(item['data']) print data['content'].encode('utf-8') time.sleep(0.5)
管道
from redis_conn import * def redis_pipeline(): pipe = REDIS_OBJ.pipeline() REDIS_OBJ.set('name', 'wangjian') REDIS_OBJ.set('role', 'SRE') pipe.execute()
Redis命令参考 http://doc.redisfans.com/