athom
athom

Reputation: 1608

Add Fallback to CircuitBreaker with Callable

I am using Spring JmsTemplate to send messages. I want to introduce resilience4j to allow me to use a Fallback so when the first call fails, it sends the message using another JmsTemplate with a different configuration.

I have a this method:

void sendMessage(JmsTemplate jmsTemplate, String body) {
    jmsTemplate.send(...);
}

The problem is that Decorators.ofCallable or Decorators.ofConsumer does not give me the withFallback option I can use the following if I change the sendMessage method to return some String.

Decorators.ofCallable(() -> sendMessage(primaryJmsTemplate, body))
    .withFallback(s -> sendMessage(secondaryJmsTemplate, body))
    .withCircuitBreaker(circuitBreaker).call();

I would rather not return a random value just to get this to work. Is there a reason why callable/consumer does not allow Fallback? Or is there a different way to achieve what I want using resilience4j?

Upvotes: 0

Views: 466

Answers (1)

athom
athom

Reputation: 1608

I changed my approach with this as I misunderstood what withFallback will achieve.

I now use the following:

try {
    circuitBreaker.executeRunnable(() -> sendMessage(primaryJmsTemplate, body));
} catch (Exception e) {
    sendMessage(secondaryJmsTemplate, body);
}

It results in closing the circuit when calls to primary fail. And then goes to secondary for a period until it retries primary again.

Upvotes: 0

Related Questions