本文 23434 pv

0

Python client for Redis安装与使用

© kekehu / 技术资源 / 2014.10.11 / 10:43 / 23434PV

redis针对python的客户端github地址:https://github.com/andymccurdy/redis-py/,打开之后最下方是使用说明,说明是英文版的,我在网上查了一下有人翻译为中文了,中文安装使用说明地址:http://www.geekso.com/component/redis-py/
我在python上主要用了redis连接池来实现redis的联接操作,我自己写了一下单例类来调用.代码下如:
#redis_class.py
import redis,json
class Credis(object):
    def __init__(self):
        self.pool = redis.ConnectionPool(host='localhost', port=6379, db=0, socket_timeout=4)
        
    def setRedis(self,key, err, status, msg):
        result = redis.Redis(connection_pool=self.pool)
        redisValue = {'err':err,'status':status,'msg':msg}
        redisValue = json.dumps(redisValue)
        return result.set(key,redisValue)
        
    def getRedis(self,key):
        result = redis.Redis(connection_pool=self.pool)
        return result.get(key)
        
credis = Credis()
使用例子:
from redis_class import credis
credis.setRedis('key',0,1,'set')
需要注意的事项:
1. Parser安装
        Parser可以控制如何解析redis响应的内容。redis-py包含两个Parser类,PythonParser和HiredisParser。默认,如果已经安装了hiredis模块,redis-py会使用HiredisParser,否则会使用PythonParser。
HiredisParser是C编写的,由redis核心团队维护,性能要比PythonParser提高10倍以上,所以推荐使用。安装方法,使用easy_install:
easy_install hiredis

2. 连接池
       redis-py使用connection pool来管理对一个redis server的所有连接,避免每次建立、释放连接的开销。默认,每个Redis实例都会维护一个自己的连接池。可以直接建立一个连接池,然后作为参数Redis,这样就可以实现多个Redis实例共享一个连接池。

3. redis pipeline机制,
      可以在一次请求中执行多个命令,这样避免了多次的往返时延。
    import redis  
    pool = redis.ConnectionPool(host='127.0.0.1', port=9212)  
    r = redis.Redis(connection_pool=pool)  
    pipe = r.pipeline()  
    pipe.set('one', 'first')  
    pipe.set('two', 'second')  
    pipe.execute()  
    pipe.set('one'. 'first').rpush('list', 'hello').rpush('list', 'world').execute()  
redis-py默认在一次pipeline中的操作是原子的,要改变这种方式,可以传入transaction=False。代码如下:
    pipe = r.pipeline(transaction=False)  

本文有 0 篇评论

发表你的见解

打开HTML 打开UBB 打开表情 隐藏 记住我
emotemotemotemotemotemotemotemotemotemotemotemotemotemotemotemotemotemotemotemot
emotemotemotemotemot