1. 程式人生 > >Python操作Redis的5種資料型別

Python操作Redis的5種資料型別

連線方式

連線方式01

import redis
# decode_responses=True 解決的是值型別是 bytes 位元組的問題
r = redis.Redis(host="192.168.66.128", port="6379", db=0,
                decode_responses=True)
print(r)

執行結果:

Redis<ConnectionPool<Connection<host=192.168.66.128,port=6379,db=0>>>

連線方式02

import redis
pool = redis.ConnectionPool(host="192.168.66.128", port=6379, db=0,
                            decode_responses=True)
redis = redis.Redis(connection_pool=pool)
print(redis)

執行結果:

Redis<ConnectionPool<Connection<host=192.168.66.128,port=6379,db=0>>>

字串型別 String

# ex 過期時間 單位為 s
redis.set("name", "Jack", ex=20)
rst = redis.get("name")
print(rst)

列表型別 list

redis.lpush("object", 'one')
redis.lpush("object", 'two')
redis.lpush("object", 'three')
redis.lpush("object", 'four')
redis.lpush("object", 'five')
redis.lpush("object", 'six')
ret = redis.lrange("object", 0, 5)
print(ret)
print(ret[::-1])
print("The length of ret is:", len(ret))

執行結果:

['six', 'five', 'four', 'three', 'two', 'one']
['one', 'two', 'three', 'four', 'five', 'six']
The length of ret is: 6

雜湊型別 hash

redis.hset("user:info", "name", "Jack")
redis.hset("user:info", "age", "20")
redis.hset("user:info", "phone", "12345678900")
redis.hset("user:info", "email", "[email protected]
") rst = redis.hgetall("user:info") print(rst)

執行結果:

{'name': 'Jack', 'age': '20', 'phone': '12345678900', 'email': '[email protected]'}

集合型別 set

redis.sadd("set", "one")
redis.sadd("set", "two")
redis.sadd("set", "three")
res = redis.smembers("set")
print(res)

執行結果:

{'one', 'two', 'three'}

有序集合型別 sorted set

redis.zadd("mark", "one", 1)
redis.zadd("mark", "two", 2)
redis.zadd("mark", "three", 3)
redis.zadd("mark", "four", 4)
redis.zadd("mark", "five", 5)
res = redis.zrange("mark", 3, 5)
print(res)

執行結果:

['four', 'five']