您好,登錄后才能下訂單哦!
當業務需要大量去連接redis或者hbase的時候,大量的連接會造成socket的大量占用,導致的結果就是服務器沒有更多的端口去分配,這種情況下的最好解決方案就是實現客戶端連接的單例模式,保持連接永遠是同一個。說到這,可能大家沒有經歷過,如果在每秒鐘插入4000條數據的話,這個現象就非常明顯了。下面就實現下python實現操作redis+hbase單例模式,有很多改進之處,根據自己業務進行調整,可以通過打印實例的ID進行驗證:
import happybase import redis class _RedisMgrSingleton(type): '''redis的單例''' def __init__(self, name, bases, dict): super(_RedisMgrSingleton, self).__init__(name, bases, dict) self._instance = {} def __call__(self, host,port,db): if not self._instance.has_key((host,port,db)): self._instance[(host,port,db)] = super(_RedisMgrSingleton, self).__call__(host,port,db) return self._instance[(host,port,db )] class HbaseSingleton(type): '''hbase的單例''' def __init__(self, name, bases, dict): super(HbaseSingleton, self).__init__(name, bases, dict) self._instance = {} def __call__(self, host,table): if not self._instance.has_key((host,table)): self._instance[(host,table)] = super(HbaseSingleton, self).__call__(host,table) return self._instance[(host,table)] class RedisMgr: "redis操作專用類" def __init__(self,host,port,db,max_connections=3): "eg: host '192.168.2.184' port 6379 db 14" self.host=host self.port=port self.db=db self.conn=redis.Redis(connection_pool= redis.ConnectionPool(host=host,port=port,db=db,max_connections=max_connections)) def run_redis_fun(self,funname,*args): fun=getattr(self.conn,funname) print args return fun(*args) def pipe(self): return self.conn.pipeline(transaction=False) __metaclass__ = _RedisMgrSingleton #元類實現單例 class HbaseOperate(object): def __init__(self,host,table): self.host = host self.table = table self.conn = happybase.Connection(self.host) self.table = self.conn.table(self.table) def run(self,fun,*args): # result =self.table.row(*args) funname = getattr(self.table,fun) return funname(*args) def cells(self,column,info,version): return self.table.cells(column,info,versions=version) __metaclass__ = HbaseSingleton #元類實現單例 conn = HbaseOperate('xxx.xx.11.8',"history_visitor_product") result = conn.cells('chenhuachao','info:visiotr',3) print result print "第一次",id(conn) conn1 = HbaseOperate('xxx.xxx.11.8',"history_visitor_product") result1= conn1.cells('chenhuachao','info:visiotr',6) print result1 print "第二次",id(conn1) #output ['test10', 'test9', 'test97'] 第一次 38014896 ['test10', 'test9', 'test97', 'test17', 'test1345\n'] 第二次 38014896
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。