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ù)文檔寫了一個帶連接池的redis client,然后生成一個實(shí)例全局使用。將一個實(shí)例,在多線程中共用測試過正常。但是多進(jìn)程情況,測試失敗
class ProcessRdeisTest(Process): def __init__(self,client):self._client = client
這樣寫,在執(zhí)行start時,會報錯,無法序列化之類。改為:
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. javascript - JS如何取對稱范圍的隨機(jī)數(shù)?2. 數(shù)據(jù)庫 - mysql如何處理數(shù)據(jù)變化中的事務(wù)?3. java - ehcache緩存用的是虛擬機(jī)內(nèi)存么?4. 關(guān)于docker下的nginx壓力測試5. java - mongodb分片集群下,count和聚合統(tǒng)計(jì)問題6. android - java 泛型不支持?jǐn)?shù)組,那么RxJava的Map集合有什么方便的手段可以定義獲得一串共同父類集合數(shù)據(jù)呢?7. dockerfile - 我用docker build的時候出現(xiàn)下邊問題 麻煩幫我看一下8. 服務(wù)器端 - 采用nginx做web服務(wù)器,C++開發(fā)應(yīng)用程序 出現(xiàn)拒絕連接請求?9. javascript - 有什么兼容性比較好的辦法來判斷瀏覽器窗口的類型?10. python - pandas按照列A和列B分組,將列C求平均數(shù),怎樣才能生成一個列A,B,C的dataframe
