示例#1
0
def main():
    nc = NATS()

    try:
        # Setting explicit list of servers in a cluster and
        # max reconnect retries.
        servers = [
            "nats://127.0.0.1:4222", "nats://127.0.0.1:4223",
            "nats://127.0.0.1:4224"
        ]
        yield nc.connect(max_reconnect_attempts=2, servers=servers)
    except ErrNoServers:
        print("No servers available!")
        return

    @tornado.gen.coroutine
    def message_handler(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        for i in range(0, 20):
            yield nc.publish(reply, "i={i}".format(i=i).encode())

    yield nc.subscribe("help.>", cb=message_handler)

    @tornado.gen.coroutine
    def request_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))

    # Signal the server to stop sending messages after we got 10 already.
    yield nc.request("help.please", b'help', expected=10, cb=request_handler)

    # Flush connection to server, returns when all messages have been processed.
    # It raises a timeout if roundtrip takes longer than 1 second.
    yield nc.flush()

    # Drain gracefully closes the connection, allowing all subscribers to
    # handle any pending messages inflight that the server may have sent.
    yield nc.drain()

    # Drain works async in the background.
    yield tornado.gen.sleep(1)
示例#2
0
def main():
    nc = NATS()

    conn_closed = tornado.concurrent.Future()

    def closed_cb():
        conn_closed.set_result(True)

    # Set pool servers in the cluster and give a name to the client.
    yield nc.connect("127.0.0.1:4222", closed_cb=closed_cb)

    @tornado.gen.coroutine
    def handler(msg):
        # Can check whether client is in draining state
        if nc.is_draining:
            print("[Status  ] Draining, will disconnect soon...")

        print("[Received] {}".format(msg.data))
        yield nc.publish(msg.reply, b'I can help')

    yield nc.subscribe("help", "workers", cb=handler)

    responses = []

    @tornado.gen.coroutine
    def send_requests():
        # Send 100 async requests and wait for all the responses.
        for i in range(0, 1000):
            try:
                response = yield nc.request("help",
                                            '[{}] help!'.format(i),
                                            timeout=0.1)
                responses.append(response)
            except:
                break

    loop.current().spawn_callback(send_requests)
    yield tornado.gen.sleep(1)

    # Gracefully close the connection and wait for closed callback to be signaled.
    yield nc.drain()
    yield conn_closed

    print("Received {} responses".format(len(responses)))