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", "2564493603@qq.com")
rst = redis.hgetall("user:info")
print(rst)

运行结果:

{'name': 'Jack', 'age': '20', 'phone': '12345678900', 'email': '2564493603@qq.com'}

集合类型 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']
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值