Skip to main content

Triggers

The ballerinax/solace connector supports event-driven integration through a solace:Listener. When a message arrives on a subscribed queue or topic, the listener dispatches it to your service's onMessage callback automatically; no manual receive loop is required.

Three components work together:

ComponentRole
solace:ListenerConnects to the Solace broker and dispatches messages to the services attached to it.
solace:ServiceDefines the onMessage and onError callbacks invoked when a message arrives or an error occurs.
solace:CallerInjected into onMessage callbacks for manual acknowledgement and transaction control.

For action-based operations, see the Action Reference.


Listener​

The solace:Listener establishes the broker connection. Each attached service subscribes to its own queue or topic through the @solace:ServiceConfig annotation.

Configuration​

ListenerConfiguration fields:

FieldTypeDefaultDescription
messageVpnstring"default"Solace message VPN name.
authBasicAuthConfiguration|KerberosConfiguration|OAuth2ConfigurationRequiredAuthentication configuration. See Supporting types.
secureSocketSecureSocket()TLS/SSL configuration.
clientNamestring()Client identifier reported to the broker. A unique name is generated when omitted.
clientDescriptionstring"Ballerina Solace Connector"A description for the application client.
transactedbooleanfalseEnable a transacted session shared by every service attached to this listener. See the note below.
compressionLevelint0ZLIB compression level (0-9, where 0 is no compression).
localhoststring()Local interface IP address to bind for outbound connections.
connectTimeoutdecimal30.0Connection timeout in seconds.
readTimeoutdecimal10.0Read timeout in seconds.
retryConfigRetryConfiguration()Reconnection retry configuration.
generateReceiveTimestampsbooleanfalsePopulate receiveTimestamp on every message delivered to a service.
calculateMessageExpirationbooleanfalsePopulate expiration on every message delivered to a service.

Important: When transacted is true, every service attached to that listener instance shares one transacted session — a commit or rollback from any one service's solace:Caller applies to messages received by all of them. Use a separate listener per service when services need independent transactions. A transacted listener doesn't support AUTO_ACK; set ackMode: CLIENT_ACK on each service and commit or roll back explicitly.

Initializing the listener​

Basic listener with username/password authentication:

import ballerinax/solace;

configurable string solaceUrl = ?;
configurable string solaceUsername = ?;
configurable string solacePassword = ?;

listener solace:Listener solaceListener = check new (
solaceUrl,
messageVpn = "default",
auth = {username: solaceUsername, password: solacePassword}
);

Listener with OAuth 2.0 authentication:

import ballerinax/solace;

configurable string solaceUrl = ?;
configurable string solaceIssuer = ?;
configurable string solaceAccessToken = ?;

listener solace:Listener solaceListener = check new (
solaceUrl,
messageVpn = "default",
auth = {issuer: solaceIssuer, accessToken: solaceAccessToken}
);

Service​

A solace:Service is a Ballerina service attached to a solace:Listener. The @solace:ServiceConfig annotation specifies which queue or topic to subscribe to, along with acknowledgement and reconnection settings. A compiler plugin validates every solace:Service at compile time: it must declare exactly one onMessage remote function and at most one onError remote function, and neither may be declared as a resource function.

@solace:ServiceConfig​

The annotation accepts either a QueueServiceConfiguration or a TopicServiceConfiguration, matching the QueueConfiguration and TopicConfiguration fields described in the Action Reference.

Callback signatures​

FunctionSignatureDescription
onMessageremote function onMessage(record {|*solace:Message; T payload;|} message, solace:Caller caller) returns solace:Error?Invoked when a message is received on the subscribed queue or topic. Narrow T to a specific type to trigger data binding.
onErrorremote function onError(solace:Error err) returns solace:Error?Optional. Invoked when an error occurs during message receipt or data binding.

Note: The caller parameter in onMessage is optional. Omit it for AUTO_ACK services, or include it (as type solace:Caller) to handle manual acknowledgments, negative acknowledgments, or transacted sessions.

Full usage example​

import ballerina/log;
import ballerinax/solace;

configurable string solaceUrl = ?;
configurable string solaceUsername = ?;
configurable string solacePassword = ?;

listener solace:Listener solaceListener = new (
solaceUrl,
messageVpn = "default",
auth = {username: solaceUsername, password: solacePassword}
);

type OrderMessage record {|
string orderId;
|};

type Message record {|
*solace:Message;
OrderMessage payload;
|};

@solace:ServiceConfig {
queueName: "orders",
ackMode: "CLIENT_ACK"
}
service solace:Service on solaceListener {

remote function onMessage(Message message, solace:Caller caller) returns solace:Error? {
do {
log:printInfo("Received order", orderId = message.payload.orderId);
check caller->ack(message);
} on fail error e {
log:printError("Failed to process order", 'error = e);
check caller->nack(message, requeue = true);
}
}

remote function onError(solace:Error err) returns solace:Error? {
log:printError("Error receiving message", 'error = err);
}
}

Caller​

The solace:Caller is injected into onMessage when the callback declares it as a second parameter. It provides manual control over acknowledgement and transacted sessions.

FunctionSignatureDescription
ackremote function ack(solace:Message message) returns solace:Error?Acknowledges a message. Required when ackMode is CLIENT_ACK on a non-transacted service.
nackremote function nack(solace:Message message, boolean requeue = true) returns solace:Error?Negatively acknowledges a message. With requeue: true (the default), the broker redelivers it; with requeue: false, the broker routes it to the dead message queue.
commitremote function 'commit() returns solace:Error?Commits the listener's transacted session. Requires transacted = true on the listener configuration.
rollbackremote function 'rollback() returns solace:Error?Rolls back the listener's transacted session; every message received since the last commit or rollback is redelivered.

Supporting types​

Message​

FieldTypeDescription
payloadanydataMessage payload.
deliveryModeDeliveryModeDIRECT (at-most-once, the default) or PERSISTENT (guaranteed).
priorityint?Message priority (0-9).
timeToLivedecimal?Time, in seconds, after which an unconsumed persistent message expires.
messageIdstring?Application-assigned message identifier.
messageTypestring?Application-defined message type label.
correlationIdstring?Correlation identifier for request/reply patterns.
replyToDestination?Destination the receiver should reply to.
senderIdstring?Identifier of the sending client.
senderTimestampint?Sender-side timestamp in milliseconds.
sequenceNumberint?Application-assigned or auto-generated sequence number.
propertiesmap<Property>?User-defined message properties. Property is boolean|int|byte|float|string|byte[]|map<Property>.
userDatabyte[]?Up to 36 bytes of application-defined binary data.
receiveTimestampint?Receive-only. Broker-side receive timestamp in milliseconds. Populated when generateReceiveTimestamps is true.
redeliveredboolean?Receive-only. Whether this delivery is a redelivery.
destinationDestination?Receive-only. The destination the message was received on.
deliveryCountint?Receive-only. Number of times this message has been delivered.
expirationint?Receive-only. Message expiration time in milliseconds. Populated when calculateMessageExpiration is true.

Destination​

public type Destination Topic|Queue;
TypeFieldsDescription
TopictopicName: stringA Solace topic destination.
QueuequeueName: stringA Solace queue destination.

Enumerations​

EnumMembersDescription
AcknowledgementModeAUTO_ACK, CLIENT_ACKWhether the connector acknowledges automatically on receipt, or the application acknowledges explicitly.
DeliveryModeDIRECT, PERSISTENTAt-most-once versus guaranteed delivery.
DurabilityDURABLE, TEMPORARYWhether a subscription endpoint is broker-provisioned and named, or created and destroyed with the connection.
ProtocolTLSV1_1, TLSV1_2, TLSV1_3TLS protocol versions accepted by SecureSocket.

Authentication​

TypeFieldsDescription
BasicAuthConfigurationusername: string, password: string?Username/password authentication. username is limited to 189 characters and password to 128 characters.
KerberosConfigurationserviceName: string = "solace", jaasLoginContext: string = "SolaceGSS", mutualAuthentication: boolean = false, jaasConfigFileReloadEnabled: boolean = falseKerberos (GSS) authentication.
OAuth2AccessTokenAuthissuer: string, accessToken: stringOAuth 2.0 authentication with a pre-obtained access token.
OidcIdTokenAuthissuer: string, oidcToken: stringOpenID Connect authentication with an ID token.

OAuth2Configuration is a union of OAuth2AccessTokenAuth and OidcIdTokenAuth.

SecureSocket​

FieldTypeDefaultDescription
trustStoreTrustStore()Truststore used to validate the broker's certificate.
keyStoreKeyStore()Keystore used for mutual TLS.
trustedCommonNamesstring[]()Up to 16 common names accepted in the broker's certificate.
excludedProtocolsProtocol[][]TLS protocol versions to exclude.
cipherSuitesSslCipherSuite[]()Allowed cipher suites. Each entry must be an SslCipherSuite value, for example ECDHE_RSA_AES256_CBC_SHA384.
validationrecord {|boolean enabled = true; boolean validateDate = true; boolean validateHostname = true;|}all trueCertificate validation controls.

TrustStore fields: location: string, password: string, format: JKS|PKCS12 = JKS. KeyStore adds keyPassword?: string and keyAlias?: string.

RetryConfiguration​

FieldTypeDefaultDescription
connectRetriesint0Number of times to retry the initial connection attempt.
connectRetriesPerHostint0Number of retries per host when multiple hosts are configured.
reconnectRetriesint3Number of times to retry reconnecting after the session goes down.
reconnectRetryWaitdecimal3.0Delay in seconds between reconnection attempts.

Errors​

TypeDescription
ErrorBase error type raised by every client, listener, and caller operation.
InactiveFlowErrorRaised by receive/receiveNoWait when the underlying flow has been shut down by the broker.
FlowDownErrorRaised by receive/receiveNoWait when the underlying flow is temporarily unavailable, for example, during reconnection.