how to use Reactor3's Context in SpringCloud Gateway

Viewed 146

I tried to use the context to set some value of Reactor3 in the filter of SpringCloud Gateway but in the controller,I can't get the value in the Context.

Actually, I am new to Reactor3. So please give me some tips or help, thank you very much!

//my GatewayFilter
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

    return chain.filter(exchange)
             .subscriberContext(ctx -> ctx.put("key", "hello gate"));
}

//my Controller
@ResponseBody
@RequestMapping("/test")
public Mono<String> test() {

     return Mono.subscriberContext()
            .map(ctx -> ctx.get("key"));
}

when I try to get the value of Context , it will throw an Exception "context is empty"

1 Answers

GatewayFilter is applied to gateway-proxied routes only and will not be applied to web controllers/routes automatically.

To achieve this you could register WebFilter instead

public class TestWebFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        return chain.filter(exchange)
                .contextWrite(ctx -> ctx.put("key", "hello gate"));
    }
}

ps

subscriberContext is deprecated. Better use contextWrite & deferContextual.

Related