python redis执行命令


from contextlib import contextmanager
from redis import Connection, ConnectionPool, ConnectionError, Redis

class RedisCli:
    def __init__(self, host, port, db, **kwargs):
        max_conn=kwargs.get('max_connections')
        if not max_conn:
            kwargs['max_connections'] = 10
            
        self._conn_pool = ConnectionPool(max_connections=kwargs.pop('max_connections'), host=host, port=port, db=db, **kwargs)
        
    @contextmanager    
    def get_handler(self):
        cli = None
        try:
            cli = Redis(connection_pool=self._conn_pool)
            yield cli
        except Exception as e:
            print("get Redis handler exception", e)
        finally:
            if cli:
                cli.close()
    
    @staticmethod
    def retry(count=3):
        def decorator(func):
            def wrapper(*args, **kwargs):
                for _ in range(count):
                    res = func(*args, **kwargs)
                    if res is not None:
                        return res
            return wrapper
        
        return decorator
    
    @retry()
    def exec(self, cmd, *args, **kwargs):
        try:
            with self.get_handler() as handler:
                if hasattr(handler, cmd):
                    method = getattr(handler, cmd)
                    return method(*args, **kwargs)
                print(f"Redis not has command:${cmd}")
        except Exception as e:
            print(f"Redis operate exception, error:{e}")
        

if __name__ == "__main__":
        
    redis_client = RedisCli("127.0.0.1", "6379", db=0, password=None)    
    print(redis_client.exec("hset", "b", "a", "1","2"))
    print(redis_client.exec('hget',name="a", key='1'))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值