使用pylibmc 来连接memcached server , 如果在使用的过程中server down , 运维可能重启memcached server , 重启之后我们的程序可以自动的重新连接server.
下面是我写的一个class 来handle 这种情况:
class MemcachedClientPro(object):
def __init__(self, host=None, port=None):
self.host, self.port = host, port
self.version = pylibmc.__version__
hosts = None
if not isinstance(host, types.ListType):
hosts = [host]
else:
hosts = host
servers = []
for host in hosts:
server = '%s:%s' % (host if host else '127.0.0.1',
port if port else '11211')
servers.append(server)
behaviors = {}
if self.version >= '1.3':
# pylibmc 1.3.0 version can handle failover
behaviors = {
'tcp_nodelay': True, 'ketama': True, 'remove_failed': 1,
'retry_timeout': 1, 'dead_timeout': 60
}
else:
behaviors = {
'tcp_nodelay': True, 'ketama': True
}
self.mc = pylibmc.Client(servers, binary=True, behaviors=behaviors)
def _reConn(self):
host, port = self.host, self.port
hosts = None
if not isinstance(host, types.ListType):
hosts = [host]
else:
hosts = host
servers = []
for host in hosts:
server = '%s:%s' % (host if host else '127.0.0.1',
port if port else '11211')
servers.append(server)
behaviors = {}
if self.version >= '1.3':
# pylibmc 1.3.0 version can handle failover
behaviors = {
'tcp_nodelay': True, 'ketama': True, 'remove_failed': 1,
'retry_timeout': 1, 'dead_timeout': 60
}
else:
behaviors = {
'tcp_nodelay': True, 'ketama': True
}
self.mc = pylibmc.Client(servers, binary=True, behaviors=behaviors)
def MemSet(self, k, v, t=0):
try:
self.mc.set(k, v, t)
except pylibmc.Error:
self._reConn()
pass
def MemGet(self, k):
try:
return self.mc.get(k)
except pylibmc.Error:
self._reConn()
return None
def MemDel(self, k):
try:
self.mc.delete(k)
except pylibmc.Error:
self._reConn()
pass
def MemMultiSet(self, mapping, t=0):
try:
return self.mc.set_multi(mapping, t)
except pylibmc.Error:
self._reConn()
return mapping.keys()
def MemMultiGet(self, keys):
try:
return self.mc.get_multi(keys)
except pylibmc.Error:
self._reConn()
return {}
def MemFlushAll(self):
try:
self.mc.flush_all()
except pylibmc.Error:
self._reConn()
pass