import ballerina/io;
import ballerina/log;
import ballerina/nats;
const string ESCAPE = "!q";
public function main() {
string message = "";
string subject = io:readln("Subject : ");
nats:Connection connection = new ();
nats:Producer producer = new (connection);
while (message != ESCAPE) {
message = io:readln("Message : ");
nats:Error? result = producer->publish(subject, <@untainted>message);
if (result is nats:Error) {
io:println("Error occurred while producing the message.");
} else {
io:println("Message published successfully.");
}
}
nats:Error? result = producer.close();
if (result is nats:Error) {
log:printError("Error occurred while closing the logical connection",
result);
} result = connection.close();
if (result is nats:Error) {
log:printError("Error occurred while closing the connection", result);
}
}# To run this sample, navigate to the directory that contains the
# `.bal` file, and execute the `ballerina run` command below.
ballerina run publisher.bal
Subject : demo
Message : Hello Ballerina!
GUID m2jS6SLLefK325DWTkkwBh received for the produced message.import ballerina/log;
import ballerina/nats;
nats:Connection connection = new;
listener nats:Listener subscription = new (connection);
@nats:SubscriptionConfig {
subject: "demo"
}
service demo on subscription { resource function onMessage(nats:Message msg, string data) {
log:printInfo("Received message : " + data);
} resource function onError(nats:Message msg, nats:Error err) {
log:printError("Error occurred in data binding", err);
}
}# To run this sample, navigate to the directory that contains the
# `.bal` file, and execute the `ballerina run` command below.
ballerina run subscriber.bal
Received message : Hello Ballerina!
Basic Publisher and SubscriberThe NATS client is used either to produce a message to a subject or consume a message from a subject. In order to execute this example, it is required that a NATS server is up and running on its default host, port, and cluster. For instructions on installing the NATS server, go to NATS Server Installation. |
|
|
|
Represents the escape character. |
|
Produces a message to a subject in the NATS sever. |
|
Initializes a producer. |
|
Produces a message to the specified subject. |
|
Closes the publisher connection. |
|
|
|
|
|
Initializes a connection. |
|
Initializes the NATS listener. |
|
Binds the consumer to listen to the messages published to the ‘demo’ subject. |
|
|
|
Prints the incoming message in the console. |
|
|