From: Michael Tremer Date: Wed, 22 Jun 2022 09:17:08 +0000 (+0000) Subject: cache: Replace memcache with Redis X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=42354733e1ce8471183af0b7de135ec86568fbfa;p=pbs.git cache: Replace memcache with Redis Signed-off-by: Michael Tremer --- diff --git a/src/buildservice/cache.py b/src/buildservice/cache.py index 18f0e10a..9b371607 100644 --- a/src/buildservice/cache.py +++ b/src/buildservice/cache.py @@ -1,43 +1,56 @@ -#!/usr/bin/python +#!/usr/bin/python3 -import logging -import memcache +import datetime +import pickle +import redis from . import base from .decorators import * -log = logging.getLogger("cache") -log.propagate = 1 - -class Client(memcache.Client): - def debuglog(self, str): - log.debug(str) - - class Cache(base.Object): - key_prefix = "pbs_" - @lazy_property - def _cache(self): - logging.debug("Connecting to memcache...") - - return Client(["localhost:11211"], debug=1) + def redis(self): + """ + Connects to a local redis server + """ + return redis.Redis(host="localhost", port=6379, db=0) def get(self, key): - log.debug("Querying for: %s" % key) - - key = "".join((self.key_prefix, key)) - - return self._cache.get(key) - - def set(self, key, val, time=60, min_compress_len=0): - key = "".join((self.key_prefix, key)) - - return self._cache.set(key, val, time=time, - min_compress_len=min_compress_len) - - def delete(self, key, time=0): - key = "".join((self.key_prefix, key)) - - return self._cache.delete(key, time=time) + """ + Fetches the value of a cached key + """ + value = self.redis.get(key) + + # Nothing found + if not value: + return + + # Decode pickled value + try: + return pickle.loads(value) + + # If the value could not be decoded, we return nothing making it look like + # no value was found in the cache. + except pickle.UnpicklingError: + return + + def set(self, key, value, expires=None): + """ + Puts something into the cache + """ + # Figure out when this expires + if expires and isinstance(expires, datetime.timedelta): + expires = expires.total_seconds() + + # Pickle value + value = pickle.dumps(value) + + # Send to redis + return self.redis.set(key, value, ex=expires) + + def delete(self, key): + """ + Deletes the key from the cache + """ + return self.redis.delete(key)