python - 如何在 Python 中订阅 NATS 主题并继续接收消息?

我尝试了下面的示例(来自 this 页面):

nc = NATS()

await nc.connect(servers=["nats://demo.nats.io:4222"])

future = asyncio.Future()

async def cb(msg):
  nonlocal future
  future.set_result(msg)

await nc.subscribe("updates", cb=cb)
await nc.publish("updates", b'All is Well')
await nc.flush()

# Wait for message to come in
msg = await asyncio.wait_for(future, 1)

但这似乎只对接收一条消息有用。我将如何订阅并继续接收消息?

我也看过 the package example , 但它似乎只是播放对话的双方,然后退出。

最佳答案

您还可以找到一个长期运行的服务示例:https://github.com/nats-io/nats.py/blob/master/examples/service.py

import asyncio
from nats.aio.client import Client as NATS

async def run(loop):
    nc = NATS()

    async def disconnected_cb():
        print("Got disconnected...")

    async def reconnected_cb():
        print("Got reconnected...")

    await nc.connect("127.0.0.1",
                     reconnected_cb=reconnected_cb,
                     disconnected_cb=disconnected_cb,
                     max_reconnect_attempts=-1,
                     loop=loop)

    async def help_request(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
            subject=subject, reply=reply, data=data))
        await nc.publish(reply, b'I can help')

    # Use queue named 'workers' for distributing requests
    # among subscribers.
    await nc.subscribe("help", "workers", help_request)

    print("Listening for requests on 'help' subject...")
    for i in range(1, 1000000):
        await asyncio.sleep(1)
        try:
            response = await nc.request("help", b'hi')
            print(response)
        except Exception as e:
            print("Error:", e)

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run(loop))
    loop.run_forever()
    loop.close()

https://stackoverflow.com/questions/63846385/

相关文章:

amazon-web-services - 服务器端加密与客户端加密 - Amazon S3

javascript - 悬停时高效的 JS 事件监听器

python - 为什么在 Pi 的整数倍处 torch.sin() 和 numpy.sin() 的

scala - 如何在不分配给 val 的情况下使用隐式调用返回的函数

python - 使用 Pandas 和 R 将序列号连接到组中的每一行

java - 阵列旋转 TLE(超出时间限制)

java - Hibernate: OneToOne: 同一类型的两个字段

python - 从数据框中删除列中以 "@"开头的单词

f# - 在 F# 中添加两个元组

python - 如何将带有元组键的 python 字典转换为 pandas 多索引数据框?