python-从redis数据库中读数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python-从redis数据库中读数据相关的知识,希望对你有一定的参考价值。

  • 读string,list,set,sort_set,hash类型的数据
import redis

class DataBase:
    def __init__(self, host, port):
        self.host = host
        self.port = port
    
    def read_string(self, key):
        try:
            r = redis.StrictRedis(host=self.host, port=self.port)
            result = r.get(key)
            return result
        except Exception as exception:
            print(exception)     
            
    def read_list(self, key, n):
        try:
            r = redis.StrictRedis(host=self.host, port=self.port)
            if n > r.llen(key):
                result = r.lrange(0, -1)
            else:
                result = r.lrange(key, 0, n)
                
            return result
        except Exception as exception:
            print(exception) 
    
    def read_set(self, key):
        try:
            r = redis.StrictRedis(host=self.host, port=self.port)
            result = r.smembers(key)
            return result
        except Exception as exception:
            print(exception)
        
    def read_hash(self, key):
        try:
            r = redis.StrictRedis(host=self.host, port=self.port)
            result = r.hgetall(key)
            return result
        except Exception as exception:
            print(exception)
    
    def read_sort_set(self, key, n):
        try:
            r = redis.StrictRedis(host=self.host, port=self.port)
            if n > r.zcard(key):
                result = r.zrange(0, -1)
            else:
                result = r.zrange(0, n)
            return result
        except Exception as exception:
            print(exception)

以上是关于python-从redis数据库中读数据的主要内容,如果未能解决你的问题,请参考以下文章

记一次线上Redis缓存击穿

Redis和memcached缓存技术

SSM+Redis瞎搞

c#如何将object类型序列化为二进制存入SQLSERVER中,并从数据库中读出来并反序列化得到object对象

storm问题记录 python 不断向kafka中写消息,spout做为消费者从kafka中读消息并emit给bolt,但是部分消息没有得到bolt的处理

如何在 Python 中异步操作数据库?aiomysqlasyncpgaioredis 使用介绍