Home  >  Article  >  Database  >  What are the methods for operating redis in python?

What are the methods for operating redis in python?

王林
王林forward
2023-06-03 13:45:03878browse

Python operates redis and uses connection pool:

redis-py uses connection pool to manage all connections to a redis server to avoid the overhead of establishing and releasing connections each time. By default, each Redis instance maintains its own connection pool. You can directly establish a connection pool and then use it as parameter Redis, so that multiple Redis instances can share a connection pool.

def getcoon():
      pool = redis.ConnectionPool(host='192.168.25.126', port=6379, password='123456', db=0)
      coon = redis.Redis(connection_pool=pool)
      coon.set('key', 'value')
      res = coon.get('key')
      return res
coon.set('sea', 'hahhahaha', ex=30)    # 过期时间单位s
set(name, value, ex=None, px=None, nx=False, xx=False)
在 Redis 中设置值,默认,不存在则创建,存在则修改。
参数:
ex - 过期时间(秒)
px - 过期时间(毫秒)
nx - 如果设置为True,则只有name不存在时,当前set操作才执行
xx - 如果设置为True,则只有name存在时,当前set操作才执行

redis uses connection pool operation

class OPRedis(object):

    def __init__(self):
        if not hasattr(OPRedis, 'pool'):
            OPRedis.getRedisCoon()  #创建redis连接
        self.coon = redis.Redis(connection_pool=OPRedis.pool)

    @staticmethod
    def getRedisCoon():
        OPRedis.pool = redis.ConnectionPool(host=redisInfo['host'], password=redisInfo['password'], port=redisInfo['port'], db=redisInfo['db'])

    """
    string类型 {'key':'value'} redis操作
    """

    def setredis(self, key, value, time=None):
        #非空即真非0即真
        if time:
            res = self.coon.setex(key, value, time)
        else:
            res = self.coon.set(key, value)
        return res

    def getRedis(self, key):
        res = self.coon.get(key).decode()
        return res

    def delRedis(self, key):
        res = self.coon.delete(key)
        return res

    """
    hash类型,{'name':{'key':'value'}} redis操作
    """
    def setHashRedis(self, name, key, value):
        res = self.coon.hset(name, key, value)
        return res


    def getHashRedis(self, name, key=None):
        # 判断key是否我为空,不为空,获取指定name内的某个key的value; 为空则获取name对应的所有value
        if key:
            res = self.coon.hget(name, key)
        else:
            res = self.coon.hgetall(name)
        return res


    def delHashRedis(self, name, key=None):
        if key:
            res = self.coon.hdel(name, key)
        else:
            res = self.coon.delete(name)
        return res

redisInfo configuration

redisInfo = {
    "host": '192.168.1.112',
    "password": '123456',
    "port": 6379,
    "db": 0
}

The above is the detailed content of What are the methods for operating redis in python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete