python redis 多进程使用
问题描述
class RedisClient(object): def __init__(self):pool = redis.ConnectionPool(host=’127.0.0.1’, port=6379)self.client = redis.StrictRedis(connection_pool=pool)
根据文档写了一个带连接池的redis client,然后生成一个实例全局使用。将一个实例,在多线程中共用测试过正常。但是多进程情况,测试失败
class ProcessRdeisTest(Process): def __init__(self,client):self._client = client
这样写,在执行start时,会报错,无法序列化之类。改为:
class ProcessRdeisTest(Process): def __init__(self):pass def run(self):self._client = RedisClient()while Ture: dosomething()
这样倒是能运行起来,不过这种连接方式正确吗?是否有更好的办法实现?
在主线程中 直接process1 = ProcessRdeisTest(’p1’) process1.start() 这种方式调用
问题解答
回答1:楼主,python redis有自己的连接池:
import redisimport threadingclass RedisPool(object): __mutex = threading.Lock() __remote = {} def __new__(cls, host, passwd, port, db):with RedisPool.__mutex: redis_key = '%s:%s:%s' % (host, port, db) redis_obj = RedisPool.__remote.get(redis_key) if redis_obj is None:redis_obj = RedisPool.__remote[redis_key] = RedisPool.new_redis_pool(host, passwd, port, db)return redis.Redis(connection_pool=redis_obj) def __init__(self, host, passwd, port, db):pass @staticmethod def new_redis_pool(host, passwd, port, db):redis_obj = redis.ConnectionPool(host=host, password=passwd, port=port, db=db, socket_timeout=3, max_connections=10) # max_connection default 2**31return redis_obj
相关文章:
1. web - nginx location 搜索算法问题!?2. windows-7 - win7下使用cmder,如何设置vim的tab为4个空格?3. thinkPHP5中获取数据库数据后默认选中下拉框的值,传递到后台消失不见。有图有代码,希望有人帮忙4. python - 怎么进行服务器性能分析5. javascript - 关于js高级程序中的问题6. python 多进程 或者 多线程下如何高效的同步数据?7. mysql - 要取出数据库中按某字段排序后的前10,20,30条数据要怎么做?8. MySQL的SELECT...FOR UPDATE究竟起什么作用9. javascript - nodejs使用mongoose连接数据库,使用post提交表单在后台,后台处理后调用res.redirect()跳转界面无效?10. media-query - 请教为何CSS3媒体查询语法不能生效?

网公网安备