Skip to content

Instantly share code, notes, and snippets.

@Bluehorn
Created March 5, 2015 11:33
Show Gist options
  • Save Bluehorn/7125f86fc12d2ae4cf7f to your computer and use it in GitHub Desktop.
Save Bluehorn/7125f86fc12d2ae4cf7f to your computer and use it in GitHub Desktop.
Redis: Starting a redis server automatically on connection failure
"""
Setup
>>> connection_pool = redis.ConnectionPool(connection_class=AutoStartConnection)
>>> client = redis.StrictRedis(connection_pool=connection_pool)
Does it work? It auto starts on first access:
>>> client.set("answer", "42")
Redis offline, starting it.
Redis start successful.
True
>>> client.get("answer")
'42'
Calling shutdown stops it:
>>> client.shutdown()
>>> redis.StrictRedis().ping() # using default connection pool to avoid autostart
Traceback (most recent call last):
...
ConnectionError: Error 111 connecting to localhost:6379. Connection refused.
It is automatically started on the next request:
>>> client.get("answer")
Redis offline, starting it.
Redis start successful.
'42'
>>> client.ping()
True
Stop it to make this rerunnable:
>>> client.shutdown()
"""
import os
import time
import redis
import doctest
import subprocess
class AutoStartConnection(redis.Connection):
# overrides redis.Connection.connect
def connect(self):
"""connect but start Redis if it is not there"""
connect = super(AutoStartConnection, self).connect
try:
connect()
except redis.exceptions.ConnectionError:
print "Redis offline, starting it."
subprocess.Popen(["redis-server"], stdout=open(os.devnull, "w"), stderr=subprocess.STDOUT)
time.sleep(1)
connect()
print "Redis start successful."
if __name__ == "__main__":
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment