Module : nats

Module overview

'ballerina/nats' provides the capability to connect with a NATS server and perform the following

Samples

NATS Producer

Following program will produce a message to a NATS server

import ballerina/nats;
import ballerina/io;

public function main() {
    nats:Producer producer = new({ host: "localhost", port: 4222, clientId: "p0" });
    var result = producer->send("demo", "Hello Ballerina !!");
    if (result is error) {
       io:println("Error occurred while producing the message.");
    } else {
       io:println("GUID "+result+" received for the produced message.");
    }
}

NATS Subscriber

Following program will consume a message from a NATS server

import ballerina/nats;
import ballerina/io;

listener nats:Listener subscription = new({ host: "localhost", port: 4222, clientId: "s0" });

@nats:ConsumerConfig { subject: "demo" }
service demo on subscription {
    resource function onMessage(nats:Message msg) {
        io:println("Recived message : " + msg.getData());
    }
}

Records

ConnectionConfig Represents the list of paramters required to establish a connection.
ConsumerConfigData Represents the list of paramters required to create a subscription.
IOError Represents an I/O error.

Objects

Connection

Represents a NATS connection.

Message

Represents a message which will be pushed from the NATS server to the consumer.

Clients

Producer

NATS producer would act as a streaming client allowing to stream messages between NATS streaming server. Producer would create a new NATS connection if a connection was not provided during the initialization.

Listeners

Listener

Represents a connection which will be used for subscription.

Annotations

ConsumerConfig

Service descriptor data generated at compile time. This is for internal use.