Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add async/await syntax example, update readme
- Loading branch information
Waldemar Quevedo
committed
May 10, 2016
1 parent
ea6b579
commit 70ffd5a
Showing
2 changed files
with
121 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
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(io_loop=loop) | ||
|
||
async def message_handler(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)) | ||
|
||
# Simple publisher and async subscriber via coroutine. | ||
sid = await nc.subscribe("foo", cb=message_handler) | ||
|
||
# Stop receiving after 2 messages. | ||
await nc.auto_unsubscribe(sid, 2) | ||
await nc.publish("foo", b'Hello') | ||
await nc.publish("foo", b'World') | ||
await nc.publish("foo", b'!!!!!') | ||
|
||
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) | ||
|
||
# Send a request and expect a single response | ||
# and trigger timeout if not faster than 50 ms. | ||
try: | ||
response = await nc.timed_request("help", b'help me', 0.050) | ||
print("Received response: {message}".format(message=response.data.decode())) | ||
except ErrTimeout: | ||
print("Request timed out") | ||
|
||
await asyncio.sleep(1, loop=loop) | ||
await nc.close() | ||
|
||
if __name__ == '__main__': | ||
loop = asyncio.get_event_loop() | ||
loop.run_until_complete(run(loop)) | ||
loop.close() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters