【redis】redis使用get及set功能,及发布订阅


import redis
import time
import threading
import json

发布 JSON 数据

data = {
   
    'name': 'Alice',
    'age': 25,
    'city': 'New York'
}
json_string = json.dumps(data)  # 将 JSON 对象转换为字符串

连接到 Redis 服务器

r = redis.StrictRedis(host='localhost', port=6379, db=0)

使用 set 和 get 方法

r.set('mykey', 'Hello Redis!')
value = r.get('mykey')
print(value.decode('utf-8'))  # 输出:Hello Redis!

发布者示例

def publisher():
    time.sleep(1)
    r.publish('channel', json_string)

订阅者示例

def subscriber():
    pubsub = r.pubsub()
    pubsub.subscribe('channel')
    for item in pubsub.listen():
        if item['type'] == 'message':
            print(item['data'].decode('utf-8'))  # 输出:Hello, subscribers!
            break

启动发布者和订阅者线程

publisher_thread = threading.Thread(target=publisher)
subscriber_thread = threading.Thread(target=subscriber)

publisher_thread.start()
subscriber_thread.start()

publisher_thread.join()
subscriber_thread.join()

相关推荐

  1. 【redis】redis使用getset功能发布订阅

    2023-12-19 03:12:02       59 阅读
  2. 【Spring Boot 3】【Redis】消息发布订阅

    2023-12-19 03:12:02       56 阅读
  3. git安装使用

    2023-12-19 03:12:02       64 阅读
  4. redis的订阅发布功能

    2023-12-19 03:12:02       33 阅读
  5. PostgreSQL的发布订阅功能

    2023-12-19 03:12:02       33 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-19 03:12:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-19 03:12:02       106 阅读
  3. 在Django里面运行非项目文件

    2023-12-19 03:12:02       87 阅读
  4. Python语言-面向对象

    2023-12-19 03:12:02       96 阅读

热门阅读

  1. uniapp蓝牙

    2023-12-19 03:12:02       57 阅读
  2. log4j日志打印配置

    2023-12-19 03:12:02       69 阅读
  3. mysql 有哪些日志文件?都有哪些作用?

    2023-12-19 03:12:02       62 阅读
  4. 力扣LeetCode75题

    2023-12-19 03:12:02       83 阅读
  5. Centos单用户模式修改root密码

    2023-12-19 03:12:02       57 阅读
  6. 51单片机控制1602LCD字符滚动三

    2023-12-19 03:12:02       61 阅读