python 单例模式 redis_python实现redis客户端单例+hbase客户端单例

当业务需要大量去连接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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值