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í)例,在多線(xiàn)程中共用測(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)?
在主線(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. mysql - sql 左連接結(jié)果union右連接結(jié)果,導(dǎo)致重復(fù)性計(jì)算怎么解決?2. 數(shù)組排序,并把排序后的值存入到新數(shù)組中3. 默認(rèn)輸出類(lèi)型為json,如何輸出html4. mysql 遠(yuǎn)程連接出錯(cuò)10060,我已經(jīng)設(shè)置了任意主機(jī)了。。。5. mysql怎么表示兩個(gè)字段的差6. MySQL的聯(lián)合查詢(xún)[union]有什么實(shí)際的用處7. mysql時(shí)間格式問(wèn)題8. php多任務(wù)倒計(jì)時(shí)求助9. mysql的主從復(fù)制、讀寫(xiě)分離,關(guān)于從的問(wèn)題10. PHP訂單派單系統(tǒng)
