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)
根據(jù)文檔寫了一個帶連接池的redis client,然后生成一個實例全局使用。將一個實例,在多線程中共用測試過正常。但是多進程情況,測試失敗
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()
這樣倒是能運行起來,不過這種連接方式正確嗎?是否有更好的辦法實現(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宿主機無法訪問容器中的服務(wù)?2. docker 下面創(chuàng)建的IMAGE 他們的 ID 一樣?這個是怎么回事????3. 在應(yīng)用配置文件 app.php 中找不到’route_check_cache’配置項4. html按鍵開關(guān)如何提交我想需要的值到數(shù)據(jù)庫5. javascript - 請問要如何修改 Node 的透明度嗎?6. require后不用使用echo返回到微信服務(wù)器 嗎7. nginx - 如何將wordpress系統(tǒng)放在二級域名下8. 想練支付寶對接和微信支付對接開發(fā)(Java),好像個人不可以,怎么弄個企業(yè)的9. css3 background顯示圖片的一部分10. vim中編輯HTML文件時換行不能縮進
