Esempio n. 1
0
async def run(loop):
    nc = Client()

    await nc.connect("localhost:4222", loop=loop)

    # publish some messages
    await nc.publish("foo", b"Hello")
    await asyncio.sleep(1.0)
    await nc.publish("foo", b"World")
    await asyncio.sleep(1.0)
    await nc.publish("foo", b"!!!!!")
    await asyncio.sleep(1.0)

    # Send a request and expect a single response
    # and trigger timeout if not faster than 1 second.
    try:
        response = await nc.request("nslookup", b"google.com", timeout=1)
        print("Received response: {message}".format(
            message=response.data.decode()))
    except ErrTimeout:
        print("Request timed out")

    # await nc.publish("foo", b"quit")
    # await asyncio.sleep(1.0)

    # Terminate connection to NATS.
    await nc.close()
Esempio n. 2
0
async def main(event_loop):
    nats_client = Client()
    await nats_client.connect(NATS_SERVERS, loop=event_loop)
    logger.info(f"Connected to NATS at {nats_client.connected_url.netloc}...")
    logger.info(f'Publishing ticks to [{TICKER_SUBJECT_NAME}]')

    while True:
        tick = make_fake_tick()
        await nats_client.publish(TICKER_SUBJECT_NAME,
                                  json.dumps(tick).encode())
        await nats_client.flush(timeout=1)
        logger.info(f'Published: {tick}')
        time.sleep(3)
Esempio n. 3
0
async def run(loop):
    nc = Client()
    await nc.connect("localhost:4222", loop=loop)

    sid = await nc.subscribe(">", cb=message_handler)

    while not EXIT:
        await asyncio.sleep(1.0)

    print("Exiting...")
    # Remove interest in subscriptions
    await nc.unsubscribe(sid)
    await nc.close()
Esempio n. 4
0
    async def get_connection(self, loop):
        self.nats = Client()

        await self.nats.connect(servers=self.urls,
                                loop=loop,
                                io_loop=loop,
                                error_cb=self.get_error_cb(),
                                disconnected_cb=self.get_disconnected_cb(),
                                closed_cb=self.get_closed_cb(),
                                reconnected_cb=self.get_reconnected_cb())

        self.state = WORKER_STATE_CONNECTED

        return self.nats
Esempio n. 5
0
async def message_handler(msg):
    global EXIT
    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))
    if subject == "nslookup":
        result = await resolve(data)
        nc = Client()
        await nc.connect("localhost:4222", loop=loop)
        await nc.publish(reply, f"{result}".encode())
        await nc.close()

    if data == "quit":
        EXIT = True
Esempio n. 6
0
import asyncio
import json
from nats.aio.client import Client

nc = Client()


async def NATS1(msg):
    req = json.loads(msg.data.decode())
    data = req["data"]
    if "TA_STATUS" not in data:
        data["TA_STATUS"] = []
    data["TA_STATUS"].append("Hello from NATS1")
    await nc.publish(
        msg.reply,
        json.dumps({
            "rval": "TPSUCCESS",
            "rcode": 0,
            "data": data
        }).encode(),
    )


async def NATS2(msg):
    data = json.loads(msg.data.decode())["data"]
    data["TA_STATUS"] = ["Hello from NATS2"]

    msg2 = await nc.request(
        "TUX1",
        json.dumps({
            "flags": "",
Esempio n. 7
0
 def __init__(self, server_addr: str, service_name: str):
     self.server_addr = server_addr
     self.service_name = service_name
     self.client = Client()
     self.subscriber_queue = asyncio.Queue()
Esempio n. 8
0
 def __init__(self, nats_url: str, loop):
     self.nats_client = Client()
     self.nats_url = nats_url
     self.loop = loop
Esempio n. 9
0
    def __init__(self):

        self.__configuration = NATSConfiguration(
            content_map=Configuration.get_instance().nats_configuration())
        self.__client: Client = Client()
Esempio n. 10
0
 def __init__(self):
     self._client = Client()
Esempio n. 11
0
import asyncio
import json
import config
from log import log
from calculator import compute
from nats.aio.client import Client

client = Client()


async def message_handler(message):
    log.info('Message received: %s' % repr(message))
    data = json.loads(message.data.decode())
    expression = data['expression']
    log.info('Evaluating expression: %s' % expression)
    result = compute(expression)
    response = json.dumps({"result": result})
    log.info('Publishing on subject "%s": %s' % (config.pub_subject, response))
    await client.publish(config.pub_subject, response.encode())


async def main(loop):
    await client.connect(config.nats_uri, loop=loop)
    await client.subscribe(config.sub_subject, cb=message_handler)


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(main(loop))
        loop.run_forever()