本文整理汇总了Python中nats.aio.client.Client.timed_request方法的典型用法代码示例。如果您正苦于以下问题:Python Client.timed_request方法的具体用法?Python Client.timed_request怎么用?Python Client.timed_request使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nats.aio.client.Client
的用法示例。
在下文中一共展示了Client.timed_request方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_timed_request
# 需要导入模块: from nats.aio.client import Client [as 别名]
# 或者: from nats.aio.client.Client import timed_request [as 别名]
def test_timed_request(self):
nc = NATS()
msgs = []
counter = 0
@asyncio.coroutine
def worker_handler(msg):
nonlocal counter
counter += 1
msgs.append(msg)
yield from nc.publish(msg.reply, 'Reply:{}'.format(counter).encode())
@asyncio.coroutine
def slow_worker_handler(msg):
yield from asyncio.sleep(0.5, loop=self.loop)
yield from nc.publish(msg.reply, b'timeout by now...')
yield from nc.connect(io_loop=self.loop)
yield from nc.subscribe("help", cb=worker_handler)
yield from nc.subscribe("slow.help", cb=slow_worker_handler)
response = yield from nc.timed_request("help", b'please', timeout=1)
self.assertEqual(b'Reply:1', response.data)
response = yield from nc.timed_request("help", b'please', timeout=1)
self.assertEqual(b'Reply:2', response.data)
with self.assertRaises(ErrTimeout):
yield from nc.timed_request("slow.help", b'please', timeout=0.1)
yield from asyncio.sleep(1, loop=self.loop)
yield from nc.close()
示例2: run
# 需要导入模块: from nats.aio.client import Client [as 别名]
# 或者: from nats.aio.client.Client import timed_request [as 别名]
def run(loop):
nc = Nats()
yield from nc.connect(io_loop=loop)
# Send a request and expect a single response and trigger timeout if not
# faster than 50 ms.
try:
response = yield from nc.timed_request("conf.host", b'host', 0.050)
print("Received response: {message}".format(message=response.data.decode()))
except ErrTimeout:
print("Request timed out")
yield from nc.publish("log.info", b'initializing')
yield from nc.publish("log.info", b'scraping item 1')
@asyncio.coroutine
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
) )
yield from nc.publish(reply, b'I can help')
# Use queue named 'workers' for distributing requests among subscribers.
yield from nc.subscribe("cmd.help", "workers", help_request)
yield from asyncio.sleep(20, loop=loop)
yield from nc.close()
示例3: go
# 需要导入模块: from nats.aio.client import Client [as 别名]
# 或者: from nats.aio.client.Client import timed_request [as 别名]
def go(loop):
nc = NATS()
try:
yield from nc.connect(io_loop=loop)
except:
pass
@asyncio.coroutine
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")
@asyncio.coroutine
def request_handler(msg):
print("[Request on '{} {}']: {}".format(msg.subject, msg.reply, msg.data.decode()))
yield from nc.publish(msg.reply, b'OK')
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", cb=request_handler)
try:
# Make a request expecting a single response within 500 ms,
# otherwise raising a timeout error.
msg = 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.")
示例4: run
# 需要导入模块: from nats.aio.client import Client [as 别名]
# 或者: from nats.aio.client.Client import timed_request [as 别名]
def run(loop):
nc = NATS()
ssl_ctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH)
ssl_ctx.protocol = ssl.PROTOCOL_TLSv1_2
ssl_ctx.load_verify_locations('../tests/certs/ca.pem')
ssl_ctx.load_cert_chain(certfile='../tests/certs/client-cert.pem',
keyfile='../tests/certs/client-key.pem')
yield from nc.connect(io_loop=loop, tls=ssl_ctx)
@asyncio.coroutine
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 = yield from nc.subscribe("foo", cb=message_handler)
# Stop receiving after 2 messages.
yield from nc.auto_unsubscribe(sid, 2)
yield from nc.publish("foo", b'Hello')
yield from nc.publish("foo", b'World')
yield from nc.publish("foo", b'!!!!!')
@asyncio.coroutine
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))
yield from nc.publish(reply, b'I can help')
# Use queue named 'workers' for distributing requests
# among subscribers.
yield from 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 = yield from nc.timed_request("help", b'help me', 0.050)
print("Received response: {message}".format(message=response.data.decode()))
except ErrTimeout:
print("Request timed out")
yield from asyncio.sleep(1, loop=loop)
yield from nc.close()
示例5: run
# 需要导入模块: from nats.aio.client import Client [as 别名]
# 或者: from nats.aio.client.Client import timed_request [as 别名]
def run(loop):
nc = NATS()
yield from nc.connect(io_loop=loop)
@asyncio.coroutine
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 = yield from nc.subscribe("foo", cb=message_handler)
# Stop receiving after 2 messages.
yield from nc.auto_unsubscribe(sid, 2)
yield from nc.publish("foo", b'Hello')
yield from nc.publish("foo", b'World')
yield from nc.publish("foo", b'!!!!!')
@asyncio.coroutine
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))
yield from nc.publish(reply, b'I can help')
# Use queue named 'workers' for distributing requests
# among subscribers.
yield from 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 = yield from nc.timed_request("help", b'help me', 0.050)
print("Received response: {message}".format(message=response.data.decode()))
except ErrTimeout:
print("Request timed out")
yield from asyncio.sleep(1, loop=loop)
yield from nc.close()
示例6: main
# 需要导入模块: from nats.aio.client import Client [as 别名]
# 或者: from nats.aio.client.Client import timed_request [as 别名]
def main(loop):
parser = argparse.ArgumentParser()
parser.add_argument('-n', '--iterations', default=DEFAULT_ITERATIONS, type=int)
parser.add_argument('-S', '--subject', default='test')
parser.add_argument('--servers', default=[], action='append')
args = parser.parse_args()
servers = args.servers
if len(args.servers) < 1:
servers = ["nats://127.0.0.1:4222"]
opts = { "servers": servers }
# Make sure we're connected to a server first...
nc = NATS()
try:
yield from nc.connect(**opts)
except Exception as e:
sys.stderr.write("ERROR: {0}".format(e))
show_usage_and_die()
@asyncio.coroutine
def handler(msg):
yield from nc.publish(msg.reply, b'')
yield from nc.subscribe(args.subject, cb=handler)
# Start the benchmark
start = time.monotonic()
to_send = args.iterations
print("Sending {0} request/responses on [{1}]".format(
args.iterations, args.subject))
while to_send > 0:
to_send -= 1
if to_send == 0:
break
yield from nc.timed_request(args.subject, b'')
if (to_send % HASH_MODULO) == 0:
sys.stdout.write("#")
sys.stdout.flush()
duration = time.monotonic() - start
ms = "%.3f" % ((duration/args.iterations) * 1000)
print("\nTest completed : {0} ms avg request/response latency".format(ms))
yield from nc.close()
示例7: test_auth_reconnect
# 需要导入模块: from nats.aio.client import Client [as 别名]
# 或者: from nats.aio.client.Client import timed_request [as 别名]
def test_auth_reconnect(self):
nc = NATS()
disconnected_count = 0
reconnected_count = 0
closed_count = 0
err_count = 0
@asyncio.coroutine
def disconnected_cb():
nonlocal disconnected_count
disconnected_count += 1
@asyncio.coroutine
def reconnected_cb():
nonlocal reconnected_count
reconnected_count += 1
@asyncio.coroutine
def closed_cb():
nonlocal closed_count
closed_count += 1
@asyncio.coroutine
def err_cb():
nonlocal err_count
err_count += 1
counter = 0
@asyncio.coroutine
def worker_handler(msg):
nonlocal counter
counter += 1
if msg.reply != "":
yield from nc.publish(msg.reply, 'Reply:{}'.format(counter).encode())
options = {
'servers': [
"nats://foo:[email protected]:4223",
"nats://hoge:[email protected]:4224"
],
'io_loop': self.loop,
'disconnected_cb': disconnected_cb,
'closed_cb': closed_cb,
'reconnected_cb': reconnected_cb,
'error_cb': err_cb,
'dont_randomize': True,
}
yield from nc.connect(**options)
self.assertTrue(nc.is_connected)
yield from nc.subscribe("one", cb=worker_handler)
yield from nc.subscribe("two", cb=worker_handler)
yield from nc.subscribe("three", cb=worker_handler)
response = yield from nc.timed_request("one", b'Help!', timeout=1)
self.assertEqual(b'Reply:1', response.data)
# Stop the first server and connect to another one asap.
yield from self.loop.run_in_executor(None, self.server_pool[0].stop)
# FIXME: Find better way to wait for the server to be stopped.
yield from asyncio.sleep(0.5, loop=self.loop)
response = yield from nc.timed_request("three", b'Help!', timeout=1)
self.assertEqual('Reply:2'.encode(), response.data)
yield from asyncio.sleep(0.5, loop=self.loop)
yield from nc.close()
self.assertEqual(1, nc.stats['reconnects'])
self.assertEqual(1, closed_count)
self.assertEqual(2, disconnected_count)
self.assertEqual(1, reconnected_count)
self.assertEqual(0, err_count)