This is how my business logic looks like:
from(incomingUri).routeId(ROUTE_ID)
...
.doTry()
.bean(stopwatch, "start")
.to(externalService)
.doCatch(NoHttpResponseException.class, ProtocolException.class, IOException.class)
.process(externalServiceExceptionProcessor(ERROR_MESSAGE_SERVICE_NOT_RESPONDING))
.doFinally()
.bean(stopwatch, "stop")
.end()
...
The Stopwatch
bean instantition:
StopWatchBean stopwatch = new StopWatchBean(new ExchangeConsumer<Stopwatch>() {
@Override
public void accept(Exchange exchange, Stopwatch stopwatch) {
Long taken = stopwatch.elapsed(MILLISECONDS);
exchange.setProperty(RESPONSE_TIME, constant(taken));
}
});
and class definition:
public class StopWatchBean {
private final Stopwatch stopwatch;
private final ExchangeConsumer<Stopwatch> onStopFunction;
public StopWatchBean(ExchangeConsumer<Stopwatch> onStopFunction) {
this.stopwatch = Stopwatch.createUnstarted();
this.onStopFunction = onStopFunction;
}
public void stop(Exchange exchange) {
if (!stopwatch.isRunning()) {
return;
}
stopwatch.stop();
onStopFunction.accept(exchange, stopwatch);
}
public void start(Exchange unused) {
stopwatch.start();
}
public void reset(Exchange unused) {
stopwatch.reset();
}
}
The Stopwatch
is from Guava and the Consumer is just a custom functional interface.
Waiting for comments.
EDIT:
I've added some simple code, like:
started = System.currentTimeMillis();
...
stopped = System.currentTimeMillis();
elapsed = stopped - started;
and made some measurements, on normal case looks good:
[xxxxxxxxxProxy ] [stopWatchStart ] [bean[StopWatchBean{elapsed=100, stopwatch=100.8 ms}] ] [ 1]
[xxxxxxxxxProxy ] [toXxxxxxxxxx ] [https://127.0.0.1:5680/xxxxxxxxx?throwExceptionOnFailure=false&bridgeEndpoint=] [ 100]
[xxxxxxxxxProxy ] [stopWatchStop ] [bean[StopWatchBean{elapsed=100, stopwatch=100.8 ms}] ] [ 3]
and on error/exception is different:
[xxxxxxxxxProxy ] [stopWatchStart ] [bean[StopWatchBean{elapsed=38, stopwatch=344.1 ms}] ] [ 1]
[xxxxxxxxxProxy ] [toXxxxxxxxxx ] [https://127.0.0.1:5680/xxxxxxxxx?throwExceptionOnFailure=false&bridgeEndpoint=] [ 37]
[xxxxxxxxxProxy ] [stopWatchStop ] [bean[StopWatchBean{elapsed=38, stopwatch=344.1 ms}] ] [ 1]
I'm puzzled, why the difference, 38 vs 344, could it be due to Camel not taking Exception handling into account?