def main(): nc = NATS() # Establish connection to the server. options = { "verbose": True, "servers": ["nats://127.0.0.1:4222"] } yield nc.connect(**options) def discover(msg=None): print("[Received]: %s" % msg.data) sid = yield nc.subscribe("discover", "", discover) # Only interested in 2 messages. yield nc.auto_unsubscribe(sid, 2) yield nc.publish("discover", "A") yield nc.publish("discover", "B") # Following two messages won't be received. yield nc.publish("discover", "C") yield nc.publish("discover", "D") # Request/Response def help_request_handler(msg): print("[Received]: %s" % msg.data) nc.publish(msg.reply, "OK, I can help!") # Susbcription using distributed queue yield nc.subscribe("help", "workers", help_request_handler) try: # Expect a single request and timeout after 500 ms response = yield nc.timed_request("help", "Hi, need help!", 500) print("[Response]: %s" % response.data) except tornado.gen.TimeoutError, e: print("Timeout! Need to retry...")
def test_close_connection(self): nc = Client() options = { "dont_randomize": True, "servers": [ "nats://*****:*****@127.0.0.1:4223", "nats://*****:*****@127.0.0.1:4224" ], "io_loop": self.io_loop } yield nc.connect(**options) self.assertEqual(True, nc._server_info["auth_required"]) log = Log() sid_1 = yield nc.subscribe("foo", "", log.persist) self.assertEqual(sid_1, 1) sid_2 = yield nc.subscribe("bar", "", log.persist) self.assertEqual(sid_2, 2) sid_3 = yield nc.subscribe("quux", "", log.persist) self.assertEqual(sid_3, 3) yield nc.publish("foo", "hello") yield tornado.gen.sleep(1.0) # Done yield nc.close() orig_gnatsd = self.server_pool.pop(0) orig_gnatsd.finish() try: a = nc._current_server # Wait and assert that we don't reconnect. yield tornado.gen.sleep(3) finally: b = nc._current_server self.assertEqual(a.uri, b.uri) self.assertFalse(nc.is_connected()) self.assertFalse(nc.is_reconnecting()) self.assertTrue(nc.is_closed()) with(self.assertRaises(ErrConnectionClosed)): yield nc.publish("hello", "world") with(self.assertRaises(ErrConnectionClosed)): yield nc.flush() with(self.assertRaises(ErrConnectionClosed)): yield nc.subscribe("hello", "worker") with(self.assertRaises(ErrConnectionClosed)): yield nc.publish_request("hello", "inbox", "world") with(self.assertRaises(ErrConnectionClosed)): yield nc.request("hello", "world") with(self.assertRaises(ErrConnectionClosed)): yield nc.timed_request("hello", "world")
def go(loop): nc = NATS() try: yield from nc.connect(io_loop=loop) except: pass def message_handler(msg): print("[Received on '{}']: {}".format(msg.subject, msg.data.decode())) try: # Interested in receiving 2 messages from the 'discover' subject. sid = yield from nc.subscribe("discover", "", message_handler) yield from nc.auto_unsubscribe(sid, 2) yield from nc.publish("discover", b'hello') yield from nc.publish("discover", b'world') # Following 2 messages won't be received. yield from nc.publish("discover", b'again') yield from nc.publish("discover", b'!!!!!') except ErrConnectionClosed: print("Connection closed prematurely") def request_handler(msg): print("[Request on '{} {}']: {}".format(msg.subject, msg.reply, msg.data.decode())) if nc.is_connected: # Subscription using a 'workers' queue so that only a single subscriber # gets a request at a time. yield from nc.subscribe("help", "workers", request_handler) try: # Make a request expecting a single response within 500 ms, # otherwise raising a timeout error. response = yield from nc.timed_request("help", b'help please', 0.500) print("[Response]: {}".format(msg.data)) # Make a roundtrip to the server to ensure messages # that sent messages have been processed already. yield from nc.flush(0.500) except ErrTimeout: print("[Error] Timeout!") # Wait a bit for message to be dispatched... yield from asyncio.sleep(1, loop=loop) # Detach from the server. yield from nc.close() if nc.last_error is not None: print("Last Error: {}".format(nc.last_error)) if nc.is_closed: print("Disconnected.")
def main(): nc = NATS() # Establish connection to the server. options = { "verbose": True, "servers": ["nats://127.0.0.1:4222"] } yield nc.connect(**options) def discover(msg=None): print("[Received]: %s" % msg.data) sid = yield nc.subscribe("discover", "", discover) # Only interested in 2 messages. yield nc.auto_unsubscribe(sid, 2) yield nc.publish("discover", "A") yield nc.publish("discover", "B") # Following two messages won't be received. yield nc.publish("discover", "C") yield nc.publish("discover", "D") # Request/Response def help_request_handler(msg): print("[Received]: %s" % msg.data) nc.publish(msg.reply.decode(), "OK, I can help!") # Susbcription using distributed queue yield nc.subscribe("help", "workers", help_request_handler) try: # Expect a single request and timeout after 500 ms response = yield nc.timed_request("help", "Hi, need help!", 500) print("[Response]: %s" % response.data) except tornado.gen.TimeoutError as e: print("Timeout! Need to retry...") # Customize number of responses to receive def many_responses(msg=None): print("[Response]: %s" % msg.data) yield nc.request("help", "please", expected=2, cb=many_responses) # Publish inbox my_inbox = new_inbox() yield nc.subscribe(my_inbox) yield nc.publish_request("help", my_inbox, "I can help too!") loop = tornado.ioloop.IOLoop.instance() yield tornado.gen.Task(loop.add_timeout, time.time() + 1) try: start = datetime.now() # Make roundtrip to the server and timeout after 1000 ms yield nc.flush(1000) end = datetime.now() print("Latency: %d µs" % (end.microsecond - start.microsecond)) except tornado.gen.TimeoutError as e: print("Timeout! Roundtrip too slow...")
def test_timed_request_timeout(self): class Parser(): def __init__(self, nc, t): self.nc = nc self.t = t def read(self, data=''): self.nc._process_pong() nc = Client() nc._ps = Parser(nc, self) yield nc.connect(io_loop=self.io_loop) with self.assertRaises(tornado.gen.TimeoutError): yield nc.timed_request("hello", "world", 500)
def main(): nc = NATS() # Establish secure connection to the server, tls options parameterize # the wrap_socket available from ssl python package. options = { "verbose": True, "servers": ["nats://127.0.0.1:4444"], "tls": { "cert_reqs": ssl.CERT_REQUIRED, "ca_certs": "./tests/configs/certs/ca.pem", "keyfile": "./tests/configs/certs/client-key.pem", "certfile": "./tests/configs/certs/client-cert.pem" } } yield nc.connect(**options) def discover(msg=None): print("[Received]: %s" % msg.data) sid = yield nc.subscribe("discover", "", discover) # Only interested in 2 messages. yield nc.auto_unsubscribe(sid, 2) yield nc.publish("discover", "A") yield nc.publish("discover", "B") # Following two messages won't be received. yield nc.publish("discover", "C") yield nc.publish("discover", "D") # Request/Response def help_request_handler(msg): print("[Received]: %s" % msg.data) nc.publish(msg.reply, "OK, I can help!") # Susbcription using distributed queue yield nc.subscribe("help", "workers", help_request_handler) try: # Expect a single request and timeout after 500 ms response = yield nc.timed_request("help", "Hi, need help!", timeout=0.500) print("[Response]: %s" % response.data) except tornado.gen.TimeoutError, e: print("Timeout! Need to retry...")
def main(): nc = NATS() # Establish secure connection to the server, tls options parameterize # the wrap_socket available from ssl python package. options = { "verbose": True, "servers": ["nats://127.0.0.1:4444"], "tls": { "cert_reqs": ssl.CERT_REQUIRED, "ca_certs": "./tests/configs/certs/ca.pem", "keyfile": "./tests/configs/certs/client-key.pem", "certfile": "./tests/configs/certs/client-cert.pem" } } yield nc.connect(**options) def discover(msg=None): print("[Received]: %s" % msg.data) sid = yield nc.subscribe("discover", "", discover) # Only interested in 2 messages. yield nc.auto_unsubscribe(sid, 2) yield nc.publish("discover", "A") yield nc.publish("discover", "B") # Following two messages won't be received. yield nc.publish("discover", "C") yield nc.publish("discover", "D") # Request/Response def help_request_handler(msg): print("[Received]: %s" % msg.data) nc.publish(msg.reply, "OK, I can help!") # Susbcription using distributed queue yield nc.subscribe("help", "workers", help_request_handler) try: # Expect a single request and timeout after 500 ms response = yield nc.timed_request( "help", "Hi, need help!", timeout=0.500) print("[Response]: %s" % response.data) except tornado.gen.TimeoutError, e: print("Timeout! Need to retry...")
def test_timed_request(self): nc = Client() yield nc.connect(io_loop=self.io_loop) class Component: def __init__(self, nc): self.nc = nc @tornado.gen.coroutine def respond(self, msg=None): yield self.nc.publish(msg.reply.decode(), "ok:1") yield self.nc.publish(msg.reply.decode(), "ok:2") yield self.nc.publish(msg.reply.decode(), "ok:3") log = Log() c = Component(nc) yield nc.subscribe(">", "", log.persist) yield nc.subscribe("help", "", c.respond) reply = yield nc.timed_request("help", "please") self.assertEqual("ok:1", reply.data.decode()) http = tornado.httpclient.AsyncHTTPClient() response = yield http.fetch('http://127.0.0.1:%d/varz' % self.server_pool[0].http_port) varz = json.loads(response.body.decode("utf-8")) self.assertEqual(18, varz['in_bytes']) self.assertEqual(28, varz['out_bytes']) self.assertEqual(4, varz['in_msgs']) self.assertEqual(6, varz['out_msgs']) self.assertEqual(2, len(log.records.keys())) self.assertEqual("please", log.records[b'help'][0].data.decode()) self.assertEqual(28, nc.stats['in_bytes']) self.assertEqual(18, nc.stats['out_bytes']) self.assertEqual(6, nc.stats['in_msgs']) self.assertEqual(4, nc.stats['out_msgs']) full_msg = '' for msg in log.records[b'help']: full_msg += msg.data.decode("utf-8") self.assertEqual('please', full_msg)
def main(): nc = NATS() # Establish connection to the server. options = {"verbose": True, "servers": ["nats://127.0.0.1:4222"]} yield nc.connect(**options) def discover(msg=None): print("[Received]: %s" % msg.data) sid = yield nc.subscribe("discover", "", discover) # Only interested in 2 messages. yield nc.auto_unsubscribe(sid, 2) yield nc.publish("discover", "A") yield nc.publish("discover", "B") # Following two messages won't be received. yield nc.publish("discover", "C") yield nc.publish("discover", "D") # Request/Response def help_request_handler(msg): print("[Received]: %s" % msg.data) nc.publish(msg.reply, "OK, I can help!") # Susbcription using distributed queue yield nc.subscribe("help", "workers", help_request_handler) try: # Expect a single request and timeout after 500 ms response = yield nc.timed_request("help", "Hi, need help!", timeout=0.500) print("[Response]: %s" % response.data) except tornado.gen.TimeoutError, e: print("Timeout! Need to retry...")