一个简单的redis缓存工具

使用redis写一个简单的缓存工具

重写redis的get,set,delete请求


import Redis
import logging
import json


def cache_retry(func):
    def decorate(*args, **kargs):
        retry_times = 2
        while retry_times != 0:
            retry_times -= 1
            self = args[0]
            try:
                return func(*args, **kargs)
            except Exception as err:
                logging.warn("execute faild: %s" % err)
                self.__init__(self.host, self.port, self.db)
        logging.warn("failed to connect to redis")
    return decorate


class Cache(Redis):
    def __init__(self, host, port, db):
        self.host = host
        self.port = port
        self.db = db
        super(Cache, self).__init__(host=self.host, port=self.port, db=self.db)

    @cache_retry
    def get(self, key, **kwargs):
        data_format = kwargs.pop('format', 'str')
        value = super(Cache, self).get(key, **kwargs)
        if data_format == 'json':
            value = json.loads(value) if value else {}
        return value

    @cache_retry
    def set(self, key, value, **kwargs):
        data_format = kwargs.pop('format', 'str')
        if data_format == 'json':
            value = json.dumps(value)
        return super(Cache, self).set(key, value, **kwargs)

    @cache_retry
    def delete(self, *args):
        return super(Cache, self).delete(*args)


if __name__ == '__main__':
    APP_CACHE = {'host': '127.0.0.1', 'port': 6380, 'db': 0}
    APP_SESSION = {'host': '127.0.0.1', 'port': 6380, 'db': 1}
    APP_AUDIT = {'host': '127.0.0.1', 'port': 6380, 'db': 2}

    cache = Cache(**APP_CACHE)
    session = Cache(**APP_SESSION)
    audit_redis = Cache(**APP_AUDIT)

你可能感兴趣的:(python学习,redis)