import redis

# 连接到 Redis
client = redis.StrictRedis(
    host='localhost',   # Redis 服务器地址
    port=6379,          # Redis 端口号
    password=None,      # 如果设置了密码,则指定密码
    decode_responses=True  # 自动解码返回的字节数据为字符串
)

# 测试连接
try:
    pong = client.ping()
    print("连接成功:", pong)
except redis.ConnectionError as e:
    print("连接失败:", e)


# 设置键值
client.set("name", "Alice")

# 获取键值
name = client.get("name")
print("Name:", name)

# 设置带过期时间的键值(10秒后自动删除)
client.set("temp_key", "value", ex=60)

# 检查键是否存在
exists = client.exists("name")
print("Name exists:", exists)

# 删除键
client.delete("name")

print('-'*30)

"""
哈希
"""
client.hset("user:1", "name", "Bob")
client.hset("user:1", "age", 30)

# 获取哈希字段的值
name = client.hget("user:1", "name")
print("User name:", name)

# 获取整个哈希
user = client.hgetall("user:1")
print("User:", user)

# 更新哈希
client.hset("user:1", "age", 31)

# 删除哈希字段
client.hdel("user:1", "age")

"""
列表
"""
# 推入列表(从左侧插入)
client.lpush("tasks", "task1")
client.lpush("tasks", "task2")

# 从右侧插入
client.rpush("tasks", "task3")

# 获取列表中的所有值
tasks = client.lrange("tasks", 0, -1)
print("Tasks:", tasks)

# 弹出列表值
task = client.lpop("tasks")
print("Popped task:", task)

"""
集合
"""
# 添加到集合
client.sadd("tags", "python", "redis", "docker")

# 获取集合的所有成员
tags = client.smembers("tags")
print("Tags:", tags)

# 检查成员是否在集合中
exists = client.sismember("tags", "python")
print("Python in tags:", exists)

# 删除集合中的成员
client.srem("tags", "docker")

"""
有序集合
"""
# 添加元素到有序集合
client.zadd("ranking", {"Alice": 50, "Bob": 75, "abc": 60})

# 获取集合中的所有元素(按分数排序)
ranking = client.zrange("ranking", 0, -1, withscores=True)
print("Ranking:", ranking)

# 获取某个成员的分数
score = client.zscore("ranking", "Alice")
print("Alice's score:", score)

# 删除有序集合中的成员
# client.zrem("ranking", "Alice")

"""
发布/订阅 (Pub/Sub)
"""
# 订阅消息
# 创建订阅对象
pubsub = client.pubsub()

# 订阅频道
pubsub.subscribe("channel1")

# 接收消息
for message in pubsub.listen():
    if message["type"] == "message":
        print(f"收到消息: {message['data']}")

# 发布消息到频道
client.publish("channel1", "Hello, Redis!")