Back to Examples

NATS JetStream client - Publish message

The nats:JetStreamClient allows you to publish messages to a specific subject. To create a nats:JetStreamClient, you need to provide a valid instance of the nats:Client. Before publishing messages, you should call the addStream function to configure the stream. This function requires a nats:JetStreamConfiguration object with the name, subjects, and storageType values. To publish messages, you can use the publishMessage method, which takes the message content and subject as arguments. This method allows you to send messages that can be received by one or more subscribers.

import ballerina/http;
import ballerinax/nats;

type Order readonly & record {
    int orderId;
    string productName;
    decimal price;
    boolean isValid;
};

service / on new http:Listener(9092) {
    private final string SUBJECT_NAME = "orders";
    private final nats:JetStreamClient orderClient;

    function init() returns error? {
        // Initiate a NATS client passing the URL of the NATS broker.
        nats:Client natsClient = check new (nats:DEFAULT_URL);

        // Initiate the NATS `JetStreamClient` at the start of the service. This will be used
        // throughout the lifetime of the service.
        self.orderClient = check new (natsClient);
        nats:StreamConfiguration config = {
            name: "demo",
            subjects: [self.SUBJECT_NAME],
            storageType: nats:MEMORY
        };
        _ = check self.orderClient->addStream(config);
    }

    resource function post orders(Order newOrder) returns http:Accepted|error {
        // Produce a message to the specified subject.
        check self.orderClient->publishMessage({
            subject: self.SUBJECT_NAME,
            content: newOrder.toString().toBytes()
        });
        return http:ACCEPTED;
    }
}

Prerequisites

Run the client program by executing the following command.

$ bal run nats_jetstream_pub.bal

Invoke the service by executing the following cURL command in a new terminal.

$ curl http://localhost:9092/orders -H "Content-type:application/json" -d "{\"orderId\": 1, \"productName\": \"Sport shoe\", \"price\": 27.5, \"isValid\": true}"

Related links

PreviousSend request message
NextSSL/TLS