python redis 多進(jìn)程使用
問(wè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ù)文檔寫(xiě)了一個(gè)帶連接池的redis client,然后生成一個(gè)實(shí)例全局使用。將一個(gè)實(shí)例,在多線程中共用測(cè)試過(guò)正常。但是多進(jìn)程情況,測(cè)試失敗
class ProcessRdeisTest(Process): def __init__(self,client):self._client = client
這樣寫(xiě),在執(zhí)行start時(shí),會(huì)報(bào)錯(cuò),無(wú)法序列化之類(lèi)。改為:
class ProcessRdeisTest(Process): def __init__(self):pass def run(self):self._client = RedisClient()while Ture: dosomething()
這樣倒是能運(yùn)行起來(lái),不過(guò)這種連接方式正確嗎?是否有更好的辦法實(shí)現(xiàn)?
在主線程中 直接process1 = ProcessRdeisTest(’p1’) process1.start() 這種方式調(diào)用
問(wèn)題解答
回答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. python - linux怎么在每天的凌晨2點(diǎn)執(zhí)行一次這個(gè)log.py文件2. 關(guān)于mysql聯(lián)合查詢(xún)一對(duì)多的顯示結(jié)果問(wèn)題3. 實(shí)現(xiàn)bing搜索工具urlAPI提交4. MySQL主鍵沖突時(shí)的更新操作和替換操作在功能上有什么差別(如圖)5. 數(shù)據(jù)庫(kù) - Mysql的存儲(chǔ)過(guò)程真的是個(gè)坑!求助下面的存儲(chǔ)過(guò)程哪里錯(cuò)啦,實(shí)在是找不到哪里的問(wèn)題了。6. windows誤人子弟啊7. 冒昧問(wèn)一下,我這php代碼哪里出錯(cuò)了???8. 如何用筆記本上的apache做微信開(kāi)發(fā)的服務(wù)器9. 我在網(wǎng)址中輸入localhost/abc.php顯示的是not found是為什么呢?10. mysql優(yōu)化 - MySQL如何為配置表建立索引?
