一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

python实现redis客户端单例+hbase客户端单例

时间:2017-01-07 编辑:简简单单 来源:一聚教程网

当业务需要大量去连接redis或者hbase的时候,大量的连接会造成socket的大量占用,导致的结果就是服务器没有更多的端口去分配,这种情况下的最好解决方案就是实现客户端连接的单例模式,保持连接永远是同一个。说到这,可能大家没有经历过,如果在每秒钟插入4000条数据的话,这个现象就非常明显了。下面就实现下python实现操作redis+hbase单例模式,有很多改进之处,根据自己业务进行调整,可以通过打印实例的ID进行验证:

 代码如下 复制代码
importhappybase importredis 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): ifnotself.__key((host,port,db)): self._instance[(host,port,db)]=super(_RedisMgrSingleton,self).__call__(host,port,db) returnself._instance[(host,port,db)] classHbaseSingleton(type): '''hbase的单例''' def__init__(self,name,bases,dict): super(HbaseSingleton,self).__init__(name,bases,dict) self._instance={} def__call__(self,host,table): ifnotself.__key((host,table)): self._instance[(host,table)]=super(HbaseSingleton,self).__call__(host,table) returnself._instance[(host,table)] classRedisMgr: "redis操作专用类" def__init__(self,host,port,db,max_connections=3): "eg:host''port6379db14" =host =port =db =(connection_pool=(host=host,port=port,db=db,max_connections=max_connections)) defrun_redis_fun(self,funname,*args): fun=getattr(,funname) printargs returnfun(*args) defpipe(self): return(transaction=False) __metaclass__=_RedisMgrSingleton#元类实现单例 classHbaseOperate(object): def__init__(self,host,table): =host =table =() =() defrun(self,fun,*args): #result=(*args) funname=getattr(,fun) returnfunname(*args) defcells(self,column,info,version): return(column,info,versions=version) __metaclass__=HbaseSingleton#元类实现单例 conn=HbaseOperate('',"history_visitor_product") result=('chenhuachao','info:visiotr',3) printresult print"第一次",id(conn) conn1=HbaseOperate('',"history_visitor_product") result1=('chenhuachao','info:visiotr',6) printresult1 print"第二次",id(conn1) #output ['test10','test9','test97'] 第一次38014896 ['test10','test9','test97','test17','test1345\n'] 第二次38014896

热门栏目