def main():
    nc = NATS()
    options = {
        "verbose":
        True,
        "servers": [
            ConfigurationManager.ConfigurationManager().getMessageUandPwd() +
            "@" +
            ConfigurationManager.ConfigurationManager().getMessageBrokerUrl() +
            ":" + str(ConfigurationManager.ConfigurationManager().
                      getMessageBrokerPort())
        ]
    }
    yield nc.connect(**options)

    def subscribeMatchServer(msg):
        matchingExec.handleMatchingMessage(json.loads(msg.data))

    yield nc.subscribe(matchingExec.getChannelName(), "job.workers",
                       subscribeMatchServer)

    matchingExec.logEvent(
        -1, "INFO", "item-matcher-worker.main",
        "Started tornado listener on " + matchingExec.getChannelName() +
        " channel.")
    matchingExec.logEvent(
        -1, "INFO", "item-matcher-worker.main",
        "template-merger on " + TEMPLATE_MERGER_CHANNEL + " channel.")
    messageSender = MessageSender.MessageSender(
        matchingExec.configCacheHandler.getMessageBrokerUrl(),
        matchingExec.configCacheHandler.getMessageBrokerPort(),
        matchingExec.configCacheHandler.getChannelName())
    messageSender.sendMessageAsync(
        messageSender.createMessageJson("SUBSCRIBE", -1,
                                        matchingExec.getChannelName(), {}))
Exemplo n.º 2
0
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):
        channel_message = message_pb2.ChannelMessage()
        channel_message.ParseFromString(msg.data)
        print("[Received]: %s" % channel_message)

    send_message = message_pb2.ChannelMessage()
    send_message.chan_num = 5
    #send_message.from = "python"
    send_message.message = "Hello, World!"

    sid = yield nc.subscribe("world.channel_message", "", discover)

    yield nc.publish("world.channel_message", send_message.SerializeToString())

    loop = tornado.ioloop.IOLoop.instance()
    yield tornado.gen.Task(loop.add_timeout, time.time() + 20)
    try:
        start = datetime.now()
        # Make roundtrip to the server and timeout after 1 second
        yield nc.flush(1)
        end = datetime.now()
        print("Latency: %d µs" % (end.microsecond - start.microsecond))
    except tornado.gen.TimeoutError, e:
        print("Timeout! Roundtrip too slow...")
Exemplo n.º 3
0
def main():
    logging.info("Connecting to NATS")
    server = "nats://%s:%d" % (natsIPAddress, natsPort)
    servers = []
    servers.append(server)
    opts = {"verbose": True, "servers": servers}
    nc = NATS()
    yield nc.connect(**opts)
    yield nc.subscribe(natsSubTopic, "", on_message)
Exemplo n.º 4
0
def main():
    nc = NATS()

    # Set pool servers in the cluster and give a name to the client.
    options = {
        "name":
        "worker",
        "servers": [
            "nats://*****:*****@127.0.0.1:4222",
            "nats://*****:*****@127.0.0.1:4223",
            "nats://*****:*****@127.0.0.1:4224"
        ]
    }

    # Explicitly set loop to use for the reactor.
    options["io_loop"] = tornado.ioloop.IOLoop.instance()

    yield nc.connect(**options)

    @tornado.gen.coroutine
    def subscriber(msg):
        yield nc.publish("discover", "pong")

    yield nc.subscribe("discover", "", subscriber)

    @tornado.gen.coroutine
    def async_subscriber(msg):
        # First request takes longer, while others are still processed.
        if msg.subject == "requests.1":
            yield tornado.gen.sleep(0.5)
        print("Processed request [{0}]: {1}".format(msg.subject, msg))

    # Create asynchronous subscription and make roundtrip to server
    # to ensure that subscriptions have been processed.
    yield nc.subscribe_async("requests.*", cb=async_subscriber)
    yield nc.flush()
    for i in range(1, 10):
        yield nc.publish("requests.{0}".format(i), "example")
    yield tornado.gen.sleep(1)

    while True:
        # Confirm stats to implement basic throttling logic.
        sent = nc.stats["out_msgs"]
        received = nc.stats["in_msgs"]
        delta = sent - received

        if delta > 2000:
            print("Waiting... Sent: {0}, Received: {1}, Delta: {2}".format(
                sent, received, delta))
            yield tornado.gen.sleep(1)

        if nc.stats["reconnects"] > 10:
            print("[WARN] Reconnected over 10 times!")

        for i in range(1000):
            yield nc.publish("discover", "ping")
Exemplo n.º 5
0
def main():
    nc = NATS()

    yield nc.connect("demo.nats.io")

    @tornado.gen.coroutine
    def subscriber(msg):
        print("Msg received on [{0}]: {1}".format(msg.subject, msg.data))

    yield nc.subscribe("foo.*.baz", "", subscriber)
    yield nc.subscribe("foo.bar.*", "", subscriber)
    yield nc.subscribe("foo.>", "", subscriber)
    yield nc.subscribe(">", "", subscriber)

    # Matches all of above
    yield nc.publish("foo.bar.baz", b"Hello World")
    yield tornado.gen.sleep(1)
Exemplo n.º 6
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)
Exemplo n.º 7
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)))