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í)例,在多線程中共用測試過正常。但是多進(jìn)程情況,測試失敗
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. android - weex 項(xiàng)目createInstanceReferenceError: Vue is not defined2. PHPExcel表格導(dǎo)入數(shù)據(jù)庫怎么導(dǎo)入3. android - 哪位大神知道java后臺(tái)的api接口的對(duì)象傳到前端后輸入日期報(bào)錯(cuò),是什么情況?求大神指點(diǎn)4. javascript - 如圖,百度首頁,查看源代碼為什么什么都沒有?5. pdo 寫入到數(shù)據(jù)庫的內(nèi)容為中文的時(shí)候?qū)懭雭y碼6. vue2.0+webpack 如何使用bootstrap?7. html - 根據(jù)用戶id實(shí)現(xiàn)論壇用戶頭像顯示的最佳實(shí)現(xiàn)8. 前端 - 為什么CSS transform-origin 屬性在 Chrome 和 Safari 中得到完全不同的效果?9. docker綁定了nginx端口 外部訪問不到10. PHP類封裝的插入數(shù)據(jù),總是插入不成功,返回false;
