python redis 多進(jìn)程使用
問題描述
class RedisClient(object): def __init__(self):pool = redis.ConnectionPool(host=’127.0.0.1’, port=6379)self.client = redis.StrictRedis(connection_pool=pool)
根據(jù)文檔寫了一個(gè)帶連接池的redis client,然后生成一個(gè)實(shí)例全局使用。將一個(gè)實(shí)例,在多線程中共用測(cè)試過正常。但是多進(jìn)程情況,測(cè)試失敗
class ProcessRdeisTest(Process): def __init__(self,client):self._client = client
這樣寫,在執(zhí)行start時(shí),會(huì)報(bào)錯(cuò),無法序列化之類。改為:
class ProcessRdeisTest(Process): def __init__(self):pass def run(self):self._client = RedisClient()while Ture: dosomething()
這樣倒是能運(yùn)行起來,不過這種連接方式正確嗎?是否有更好的辦法實(shí)現(xiàn)?
在主線程中 直接process1 = ProcessRdeisTest(’p1’) process1.start() 這種方式調(diào)用
問題解答
回答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
相關(guān)文章:
1. docker 下面創(chuàng)建的IMAGE 他們的 ID 一樣?這個(gè)是怎么回事????2. 運(yùn)行python程序時(shí)出現(xiàn)“應(yīng)用程序發(fā)生異常”的內(nèi)存錯(cuò)誤?3. node.js - mongodb查找子對(duì)象的名稱為某個(gè)值的對(duì)象的方法4. html5 - datatables 加載不出來數(shù)據(jù)。5. javascript - QQ第三方登錄的問題6. 前端 - @media query 使用出現(xiàn)的問題?7. javascript - 在 model里定義的 引用表模型時(shí),model為undefined。8. 利用IPMI遠(yuǎn)程安裝centos報(bào)錯(cuò)!9. 測(cè)試自動(dòng)化html元素選擇器元素ID或DataAttribute [關(guān)閉]10. html5和Flash對(duì)抗是什么情況?

網(wǎng)公網(wǎng)安備