开发者

SpringCloud Webflux过滤器增加header传递方式

目录
  • Webflux过滤器增加header传递
  • Webflux过滤器使用
  • 总结

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).bu编程客栈ild();
        return chain.filter(mutatedExchange);
    }
}
 
 
## Kotlin 的方式
@Component
class AuthorizationF编程客栈il开发者_Go学习ter : 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 vFlvzIEXrequest =  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 chttp://www.devze.comhain.filter(exchange);
        }
    }
}

webFlux将指定的错误信息通过json格式返回给前端

exchange.getResponse().writeWith(Flux.just(exchange.getResponse().bufferFactory().wrap(JsonUtil.toJson(new BaseErrorVO().fail(e.getMessageCode(),e.getSystemMessage())).getBytes())));

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜