SpringCloud Webflux过滤器增加header传递方式
低头确望水中月亮 人气:0Webflux过滤器增加header传递
webflux 使用异步非阻塞的方式,传递Header还需要我们自己增加代码传递:
定义过滤器,便携下面的配置可以尝试一下header的传递到后面的服务中。
@Component public class AuthorizationFilter implements WebFilter { @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { ServerHttpRequest mutatedRequest = exchange.getRequest().mutate().header(HttpHeaders.AUTHORIZATION, "Bearer " + authHeader).build(); ServerWebExchange mutatedExchange = exchange.mutate().request(mutatedRequest).build(); return chain.filter(mutatedExchange); } } ## Kotlin 的方式 @Component class AuthorizationFilter : WebFilter { override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> { val mutatedRequest = exchange.request.mutate().header(HttpHeaders.AUTHORIZATION, "Bearer $authHeader").build() val mutatedExchange = exchange.mutate().request(mutatedRequest).build() return chain.filter(mutatedExchange) } }
Webflux过滤器使用
下面是简单处理token的例子
@Component @Order(value = 2) public class AuthFilter implements WebFilter { @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); //ServerHttpResponse response = exchange.getResponse(); String token = request.getHeaders().getFirst("token"); if(null == token){ /*http头中没有appKey,修改请求的目标url为/auth/error request.mutate返回一个请求构建器(builder design pattern),path方法修改请求的url,build方法返回新的request */ ServerHttpRequest authErrorReq = request.mutate().path("/auth/error").build(); //erverWebExchange.mutate类似,构建一个新的ServerWebExchange ServerWebExchange authErrorExchange = exchange.mutate().request(authErrorReq).build(); return chain.filter(authErrorExchange); } else{ return chain.filter(exchange); } } }
webFlux将指定的错误信息通过json格式返回给前端
exchange.getResponse().writeWith(Flux.just(exchange.getResponse().bufferFactory().wrap(JsonUtil.toJson(new BaseErrorVO().fail(e.getMessageCode(),e.getSystemMessage())).getBytes())));
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
加载全部内容