Skip to content

Instantly share code, notes, and snippets.

@Elyorbe
Created October 27, 2022 08:22
Show Gist options
  • Save Elyorbe/c7cc5f28d0fced86dbd054dce0a9e206 to your computer and use it in GitHub Desktop.
Save Elyorbe/c7cc5f28d0fced86dbd054dce0a9e206 to your computer and use it in GitHub Desktop.
RequestContextHolder support for reactive Spring Applications
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;
@Component
@Order(value = Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public class ReactiveRequestContextFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
return chain.filter(exchange)
.contextWrite(ctx -> ctx.put(ReactiveRequestContextHolder.CONTEXT_KEY, request));
}
}
import org.springframework.http.server.reactive.ServerHttpRequest;
import reactor.core.publisher.Mono;
public class ReactiveRequestContextHolder {
public static final Class<ServerHttpRequest> CONTEXT_KEY = ServerHttpRequest.class;
public static Mono<ServerHttpRequest> getRequest() {
return Mono.deferContextual(ctx ->
Mono.just(ctx.get(CONTEXT_KEY)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment