Skip to content

Instantly share code, notes, and snippets.

@dcrosta
Created March 10, 2014 20:18
Show Gist options
  • Save dcrosta/9473409 to your computer and use it in GitHub Desktop.
Save dcrosta/9473409 to your computer and use it in GitHub Desktop.
import time
import pymemcache.client
import pymemcache.serde
class PoliteClient(pymemcache.client.Client):
"""A sublcass of :class:`~pymemcache.client.Client`, which
waits a configurable period before attempting to reconnect
after a disconnect.
"""
def __init__(self, server, timeout=1.0, connect_timeout=1.0, reconnect_delay=10):
super(PoliteClient, self).__init__(
server=server,
timeout=timeout,
connect_timeout=connect_timeout,
serializer=pymemcache.serde.python_memcache_serializer,
deserializer=pymemcache.serde.python_memcache_deserializer,
ignore_exc=True,
no_delay=True, # NOTE: please do not remove this
)
self._reconnect_delay = reconnect_delay
self._reconnect_after = 0
def _connect(self):
if time.time() >= self._reconnect_after:
self._reconnect_after = 0
try:
return super(PoliteClient, self)._connect()
except:
# if we couldn't reconnect, wait more
self.close()
def close(self):
super(PoliteClient, self).close()
if self._reconnect_after == 0:
self._reconnect_after = time.time() + self._reconnect_delay
# To maintain compatibility with python-memcached, we
# semi-silently fail if the server was disconnected
def _misc_cmd(self, cmd, cmd_name, noreply):
if self._reconnect_after and time.time() < self._reconnect_after:
return 0
return super(PoliteClient, self)._misc_cmd(cmd, cmd_name, noreply)
def _store_cmd(self, name, key, expire, noreply, data, cas=None):
if self._reconnect_after and time.time() < self._reconnect_after:
# when things have set noreply=True, they acknowledge
# that they don't know whether the command succeeded
return noreply
return super(PoliteClient, self)._store_cmd(name, key, expire, noreply, data, cas=cas)
def _fetch_cmd(self, name, keys, expect_cas):
if self._reconnect_after and time.time() < self._reconnect_after:
return {}
return super(PoliteClient, self)._fetch_cmd(name, keys, expect_cas)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment