python连接redis的两种方式

    技术2022-07-11  74

    前言

    ------先安装redis库 ------pip install redis

    直接连接,用redis库中的Redis或者StrictRedis连接池连接,跟直接连接操作步骤相似,只是要传入pool参数

    代码

    第一种 from redis import Redis ''' 一般连接,使用Redis连接 ''' # 这里使用Redis db = Redis(host="localhost", port=6379, db=0, decode_responses=True) # 操作结果的数据类型默认为二进制,除非decode_responses=True resu = db.smembers('set1') print(resu) from redis import StrictRedis ''' 一般连接,使用StrictRedis连接 ''' # 这里使用StrictRedis db = StrictRedis(host="localhost", port=6379, db=0, decode_responses=True) 第二种 from redis import ConnectionPool from redis import Redis ''' 使用连接池 连接redis库的 Redis ''' # 创建pool pool = ConnectionPool(host='localhost', port=6379, db=0, decode_responses=True) # 传入pool db = Redis(connection_pool=pool) # 下方是获取操作结果 resu = db.hget('mark', "name") resu2 = db.hmget('mark', 'name', "age", "h") resu3 = db.hgetall("mark") # 下方是输出操作结果 print(resu, type(resu), sep=" 类型是: ") print(resu2, type(resu2), sep=" 类型是: ") print(resu3, type(resu3), sep=" 类型是: ") from redis import ConnectionPool from redis import StrictRedis ''' 使用连接池连接 redis库的 StrictRedis ''' pool = ConnectionPool(host="localhost", port=6379, db=0, decode_responses=True) db = StrictRedis(connection_pool=pool)
    Processed: 0.011, SQL: 9