Search code examples
javaserviceballerina

How can I make nats:Listener use a custom ConnectionConfiguration object in Ballerina?


I am using the code provided on the official project page at https://ballerina.io/learn/by-example/nats-basic-sub/.

The code looks like this:

    import ballerina/log;
    import ballerinax/nats;

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

    // Binds the consumer to listen to the messages published to the 'orders.valid' subject.
    service "orders.valid" on new nats:Listener(nats:DEFAULT_URL) {

        remote function onMessage(Order 'order) returns error? {
            if 'order.isValid {
                log:printInfo(string `Received valid order for ${'order.productName}`);
            }
        }
    }

I need to annotate or pass a ConnectionConfiguration object to the service's listener so that I can modify the nats:RetryConfig object. My goal is to make the service keep trying to connect to the NATS server every 5 seconds without interruption if the NATS server becomes unavailable until the NATS server becomes available again. I think this can be achieved by setting maxReconnect to -1 and reconnectWait to 5.

I looked for some helpers and/or callbacks in the service code but I think it is not the right approach.

How can I do this? Can it be done with any annotations on the service?

Thanks!


Solution

  • You can modify the code to pass the ConnectionConfiguration record to the listener initialisation with the values maxReconnect and reconnectWait as given below.

    import ballerina/log;
    import ballerinax/nats;
    
    public type Order record {
        int orderId;
        string productName;
        decimal price;
        boolean isValid;
    };
    
    final nats:ConnectionConfiguration & readonly config = {
        retryConfig: {maxReconnect: -1, reconnectWait: 5}
    };
    
    service "orders.valid" on new nats:Listener(nats:DEFAULT_URL, config) {
    
        remote function onMessage(Order 'order) returns error? {
            if 'order.isValid {
                log:printInfo(string `Received valid order for ${'order.productName}`);
            }
        }
    }
    

    OR

    import ballerina/log;
    import ballerinax/nats;
    
    public type Order record {
        int orderId;
        string productName;
        decimal price;
        boolean isValid;
    };
    
    service "orders.valid" on new nats:Listener(nats:DEFAULT_URL, {retryConfig: {maxReconnect: -1, reconnectWait: 5}}) {
    
        remote function onMessage(Order 'order) returns error? {
            if 'order.isValid {
                log:printInfo(string `Received valid order for ${'order.productName}`);
            }
        }
    }