给网友朋友们带来一篇相关的编程文章,网友禄银柳根据主题投稿了本篇教程内容,涉及到SpringCloud Webflux、Webflux过滤器、Webflux增加header传递、SpringCloud Webflux过滤器增加header传递相关内容,已被159网友关注,下面的电子资料对本篇知识点有更加详尽的解释。
SpringCloud Webflux过滤器增加header传递
Webflux过滤器增加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())));
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持码农之家。