如何解决如何在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,但它似乎只是在谈话的双方进行,然后退出。
解决方法
对python不太了解,但看起来您只是在等待一条消息,程序结束。您应该查看订户示例here。如您所见,有一个循环可以永远等待或等待SIGTERM信号。
,您还可以找到长期运行的服务示例: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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。