Skip to content

Commit

Permalink
Merge pull request #225 from nats-io/example-doc-updates
Browse files Browse the repository at this point in the history
Doc updates and version bump
  • Loading branch information
wallyqs authored Nov 23, 2021
2 parents b437e48 + 90295d4 commit 83763fc
Show file tree
Hide file tree
Showing 24 changed files with 475 additions and 600 deletions.
31 changes: 23 additions & 8 deletions examples/advanced.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,29 @@
import asyncio
import nats
from nats.aio.errors import ErrTimeout, ErrNoServers
from nats.errors import TimeoutError, NoServersError

async def main():
async def disconnected_cb():
print('Got disconnected!')

async def reconnected_cb():
print(f'Got reconnected to {nc.connected_url.netloc}')

async def error_cb(e):
print(f'There was an error: {e}')

async def closed_cb():
print('Connection is closed')

async def run():
try:
# Setting explicit list of servers in a cluster.
nc = await nats.connect(servers=["nats://127.0.0.1:4222", "nats://127.0.0.1:4223", "nats://127.0.0.1:4224"])
except ErrNoServers as e:
nc = await nats.connect("localhost:4222",
error_cb=error_cb,
reconnected_cb=reconnected_cb,
disconnected_cb=disconnected_cb,
closed_cb=closed_cb,
)
except NoServersError as e:
print(e)
return

Expand All @@ -31,7 +48,7 @@ async def request_handler(msg):
# Flush connection to server, returns when all messages have been processed.
# It raises a timeout if roundtrip takes longer than 1 second.
await nc.flush(1)
except ErrTimeout:
except TimeoutError:
print("Flush timeout")

await asyncio.sleep(1)
Expand All @@ -41,6 +58,4 @@ async def request_handler(msg):
await nc.drain()

if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
loop.close()
asyncio.run(main())
202 changes: 0 additions & 202 deletions examples/aiohttp-example.py

This file was deleted.

10 changes: 4 additions & 6 deletions examples/basic.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import asyncio
import nats
from nats.aio.errors import ErrConnectionClosed, ErrTimeout, ErrNoServers
from nats.errors import ConnectionClosedError, TimeoutError, NoServersError

async def run():
async def main():
# It is very likely that the demo server will see traffic from clients other than yours.
# To avoid this, start your own locally and modify the example to use it.
nc = await nats.connect("nats://demo.nats.io:4222")
Expand Down Expand Up @@ -53,7 +53,7 @@ async def help_request(msg):
response = await nc.request("help", b'help me', timeout=0.5)
print("Received response: {message}".format(
message=response.data.decode()))
except ErrTimeout:
except TimeoutError:
print("Request timed out")

# Remove interest in subscription.
Expand All @@ -63,6 +63,4 @@ async def help_request(msg):
await nc.drain()

if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
loop.close()
asyncio.run(main())
25 changes: 11 additions & 14 deletions examples/client.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import asyncio
from datetime import datetime
from nats.aio.client import Client as NATS
from nats.aio.errors import ErrConnectionClosed, ErrTimeout
from nats.errors import ConnectionClosedError, TimeoutError


class Client:
def __init__(self, nc, loop=asyncio.get_event_loop()):
def __init__(self, nc):
self.nc = nc
self.loop = loop

async def message_handler(self, msg):
print(f"[Received on '{msg.subject}']: {msg.data.decode()}")
Expand All @@ -21,24 +20,24 @@ async def start(self):
try:
# It is very likely that the demo server will see traffic from clients other than yours.
# To avoid this, start your own locally and modify the example to use it.
# await self.nc.connect(servers=["nats://127.0.0.1:4222"], loop=self.loop)
await self.nc.connect(servers=["nats://demo.nats.io:4222"], loop=self.loop)
# await self.nc.connect(servers=["nats://127.0.0.1:4222"])
await self.nc.connect(servers=["nats://demo.nats.io:4222"])
except:
pass

nc = self.nc
try:
# Interested in receiving 2 messages from the 'discover' subject.
sid = await nc.subscribe("discover", "", self.message_handler)
await nc.auto_unsubscribe(sid, 2)
sub = await nc.subscribe("discover", "", self.message_handler)
await sub.unsubscribe(2)

await nc.publish("discover", b'hello')
await nc.publish("discover", b'world')

# Following 2 messages won't be received.
await nc.publish("discover", b'again')
await nc.publish("discover", b'!!!!!')
except ErrConnectionClosed:
except ConnectionClosedError:
print("Connection closed prematurely")

if nc.is_connected:
Expand All @@ -51,20 +50,19 @@ async def start(self):
# Make a request expecting a single response within 500 ms,
# otherwise raising a timeout error.
start_time = datetime.now()
response = await nc.timed_request("help", b'help please',
0.500)
response = await nc.request("help", b'help please', 0.500)
end_time = datetime.now()
print(f"[Response]: {response.data}")
print("[Duration]: {}".format(end_time - start_time))

# Make a roundtrip to the server to ensure messages
# that sent messages have been processed already.
await nc.flush(0.500)
except ErrTimeout:
except TimeoutError:
print("[Error] Timeout!")

# Wait a bit for messages to be dispatched...
await asyncio.sleep(2, loop=self.loop)
await asyncio.sleep(2)

# Detach from the server.
await nc.close()
Expand All @@ -78,5 +76,4 @@ async def start(self):

if __name__ == '__main__':
c = Client(NATS())
c.loop.run_until_complete(c.start())
c.loop.close()
asyncio.run(c.start())
34 changes: 34 additions & 0 deletions examples/connect.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import asyncio
import nats
from nats.errors import TimeoutError, NoServersError

async def main():
async def disconnected_cb():
print('Got disconnected!')

async def reconnected_cb():
print(f'Got reconnected to {nc.connected_url.netloc}')

async def error_cb(e):
print(f'There was an error: {e}')

async def closed_cb():
print('Connection is closed')

nc = await nats.connect('localhost:4222',
error_cb=error_cb,
reconnected_cb=reconnected_cb,
disconnected_cb=disconnected_cb,
closed_cb=closed_cb,
)

async def handler(msg):
print(f'Received a message on {msg.subject} {msg.reply}: {msg.data}')
await msg.respond(b'OK')
sub = await nc.subscribe('help.please', cb=handler)

resp = await nc.request('help.please', b'help')
print('Response:', resp)

if __name__ == '__main__':
asyncio.run(main())
Loading

0 comments on commit 83763fc

Please sign in to comment.