Given a org.springframework.web.server.WebFilter - what are some best ways to start a "longer running" thread without blocking the REST response coming back to the consumer. The long running process in my case will be an IO operation persisting some data in a database. It wont really take "very long" but I do not want to impact the response time.
Ive tried two different approaches and they seem to both work, not sure which one is considered "correct".
// approach #1
@Override
@NonNull
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
String requestId = UUID.randomUUID().toString();
String correlationId = UUID.randomUUID().toString();
return chain.filter(exchange)
.doAfterTerminate(()->{
Mono.fromRunnable(new LongRunningTask(requestId, 10000L))
.subscribeOn(Schedulers.boundedElastic())
.subscribe();
})
.contextWrite(Context.of(
KEY_REQUEST_ID, requestId,
KEY_CORRELATION_ID, correlationId
));
}
// approach #2
@Override
@NonNull
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
String requestId = UUID.randomUUID().toString();
String correlationId = UUID.randomUUID().toString();
return chain.filter(exchange)
.publishOn(Schedulers.boundedElastic())
.then(Mono.fromRunnable(new LongRunningTask(requestId, 10000L)).then())
.contextWrite(Context.of(
KEY_REQUEST_ID, requestId,
KEY_CORRELATION_ID, correlationId
));
}