request reply有两种模式:
• one to one 默认模式
1条消息,N个订阅者,消息发送方,仅会收到一条回执记录(因为消息发送方收到回执消息后,就自动断开了对回执消息的订阅。),即使N个订阅都都收到了消息。注意:pub/sub和queue模式的不同
• one to many 非默认模式,需要自己实现
1条消息,N个订阅者,消息发送方,可以自己设定一个数量限制N,接受到N个回执消息后,断开对回执消息的订阅。
请求方:
import asyncio
from nats.aio.client import Client as NATS
from nats.aio.errors import ErrConnectionClosed, ErrTimeout, ErrNoServers
async def run(loop):
nc = NATS()
await nc.connect("192.168.1.106:4222", loop=loop)
try:
response = await nc.request("help", b'help me', timeout=1)
print("Received response: {message}".format(
message=response.data.decode()))
except ErrTimeout:
print("Request timed out")
# Remove interest in subscription.
# Terminate connection to NATS.
await nc.close()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(run(loop))
loop.close()
响应方:
#coding=utf-8
import asyncio
from nats.aio.client import Client as NATS
from nats.aio.errors import ErrConnectionClosed, ErrTimeout, ErrNoServers
async def run(loop):
nc = NATS()
await nc.connect("192.168.1.106:4222", 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))
datas='''
this is a test
'''
#网络编程中,服务器和浏览器只认bytes 类型数据。
datas=datas.encode('utf-8')
# await nc.publish(reply, b'I can help')
await nc.publish(reply,datas)
sid = await nc.subscribe("help", "workers", help_request)
# await nc.unsubscribe(sid)
# await nc.close()
print(sid)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(run(loop))
try:
loop.run_forever()
finally:
loop.close()