Spring Cloud Gateway实战WebFlux解析请求体及抛出指定错误代码和信息

概述

基于Spring Cloud开发微服务时,使用Spring Cloud原生自带的Gateway作为网关,所有请求都需要经过网关服务转发。

为了防止恶意请求刷取数据,对于业务请求需要进行拦截,故而可在网关服务增加拦截过滤器。基于此,有如下源码:


@Slf4j
@Component
public class BlockListFilter extends AbstractGatewayFilterFactory {private static final String DIALOG_URI = "/dialog/nextQuestion";@Resourceprivate AssessmentBlockListService assessmentBlockListService;@Lazy@Resourceprivate RemoteUserService remoteUserService;@Lazy@Resourceprivate RemoteRcService remoteRcService;@Lazy@Autowiredprivate RemoteOAuthService remoteOAuthService;@Value("${blockListSwitch:true}")private Boolean blockListSwitch;@Overridepublic GatewayFilter apply(Object config) {return (exchange, chain) -> {ServerHttpResponse response = exchange.getResponse();response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);ServerHttpRequest serverHttpRequest = exchange.getRequest();String uri = serverHttpRequest.getURI().getPath();HttpHeaders httpHeaders = serverHttpRequest.getHeaders();// 只处理相关urlif (blockListSwitch && StringUtils.equalsIgnoreCase(uri, DIALOG_URI)) {String token = httpHeaders.getFirst("Authorization");String pureToken = StringUtils.replaceIgnoreCase(token, "Bearer ", "");BaseUserInfo baseUserInfo = UserUtil.getBaseUserInfo(pureToken);if (baseUserInfo == null) {log.warn("传入的token非法:{}", token);return chain.filter(exchange);}// 从JWT token中解析用户信息(不含mobile等敏感信息)String channel = baseUserInfo.getChannel();String userKey = baseUserInfo.getUserkey();UserParam userParam = new UserParam();userParam.setKey(userKey);userParam.setChannel(channel);// Feign远程请求user服务获取mobile信息Response<UserAccountVO> userAccountResponse = remoteUserService.baseQuery(userParam);if (userAccountResponse.getCode() != 0) {log.warn("未获取到userKey={}的用户信息!", userKey);return chain.filter(exchange);}UserAccountVO userAccountVO = userAccountResponse.getData();log.info("blocklist filter user={}", JsonUtil.beanToJson(userAccountVO));String mobile = userAccountVO.getMobile();if (StringUtils.isNotBlank(userKey)) {// 具体的拦截业务逻辑this.process(uri, userKey, mobile, channel, pureToken);}return chain.filter(exchange);}return chain.filter(exchange);};}private String process(String uri, String userKey, String mobile, String channel, String token) {DetectUserDTO detectUserDTO = new DetectUserDTO();detectUserDTO.setChannel(channel);detectUserDTO.setMobile(mobile);detectUserDTO.setUserKey(userKey);detectUserDTO.setUri(uri);Response<DetectUserVO> detectUserVOResponse = remoteRcService.detectUser(detectUserDTO);if (detectUserVOResponse.getCode() != 0) {log.warn("mobile={} 风控接口返回异常:{}", mobile, JsonUtil.beanToJson(detectUserVOResponse));return null;}DetectUserVO detectUserVO = detectUserVOResponse.getData();if (detectUserVO.getIsInAllowList()) {log.info("在白名单中,放行");} else if (detectUserVO.getIsInBlockList()) {log.info("在黑名单中,拦截处理...");this.logout(token);return "当前手机号问诊次数已达今日上限!";}return null;}private void logout(String token) {// 强制下线,踢出登录态LogoutDto logoutDto = new LogoutDto();logoutDto.setToken(pureToken);remoteOAuthService.logout(logoutDto);}
}

上面的代码只是实现:判断流量请求URL,进而判断用户是否触发风控黑名单机制,如果触发黑名单,则踢出登录态强制用户下线,即用户不能使用App。

需求

异常捕获

上面的踢出登录态做法过于简单粗暴,App有若干个功能模块,某些请求URL触发黑名单机制,就强制用户下线,不能使用App其他功能。应该允许用户使用除了触发黑名单模块的其他模块功能。当然,对于是否强制下线的交互设计,每个人有每个人的看法。

就我遇到的情况来细说,痛点在于,前端(所谓大前端概念,含iOS和安卓App)同学针对此种情况直接返回统一的错误页:【抱歉,请返回再试一次!】,并且这个页面没有任何UI设计,仅仅是前面提到的一句提示文案。用户看到这个文案,会重新登录(因为后端做了踢出登录态逻辑),App成功后经过网关校验,发现用户依旧触发黑名单,然后再次踢出登录态,陷入死循环。

基于此,做如下改造:不踢出登录态,可以继续使用其他模块功能,在使用某个触发黑名单机制的模块时后端返回错误码,前端弹窗提示【无法使用此功能】。

故而对上面的代码进行调整:

String msg = this.process(uri, userKey, mobile, channel, pureToken,);
if (StringUtils.isNotBlank(msg)) {return Mono.error(new CustomException(BlockTypeEnum.getCodeByMsg(msg), msg));
}

本地启动Gateway网关服务,postman模拟请求,得到接口返回数据:
在这里插入图片描述
咦?怎么Code不是枚举类里定义的错误文案msg对应的错误码,而是500呢?

看代码,发现有个继承DefaultErrorWebExceptionHandler的JsonErrorWebExceptionHandler类,那这个类也需要调整:


@Slf4j
public class JsonErrorWebExceptionHandler extends DefaultErrorWebExceptionHandler {public JsonErrorWebExceptionHandler(ErrorAttributes errorAttributes,ResourceProperties resourceProperties,ErrorProperties errorProperties,ApplicationContext applicationContext) {super(errorAttributes, resourceProperties, errorProperties, applicationContext);}@Overrideprotected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {Map<String, Object> errorAttributes = new HashMap<>(8);Throwable error = super.getError(request);errorAttributes.put("message", error.getMessage());if (error instanceof CustomException) {errorAttributes.put("code", ((CustomException) error).getCode());} else {errorAttributes.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());}errorAttributes.put("method", request.methodName());errorAttributes.put("path", request.path());log.warn("网关异常,path:{},method:{},message:{}", request.path(), request.methodName(), error.getMessage());return errorAttributes;}@Overrideprotected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);}@Overrideprotected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {// 这里其实可以根据errorAttributes里面的属性定制HTTP响应码return HttpStatus.INTERNAL_SERVER_ERROR;}
}

经过调整后,断点调试,万事大吉:
在这里插入图片描述
但是!!!

后来在和前端联调时才发现有点不对劲:
在这里插入图片描述
如上图,枚举类里有几个code,每个code都有对应的系统功能模块黑名单msg。之前没有注意到右上角的接口状态码是500,这个500表示请求未成功。也就是说,接口未成功,接口响应码是自定义的code也没啥用。status必须得是200、204、202这种才行。

总结一下:虽然使用Mono.error()返回业务自定义错误信息,但错误代码9996被转为500。

继续排查。找到下面参考2里的文章,做如下调整:

String msg = this.process(uri, userKey, mobile, channel, pureToken,);
if (StringUtils.isNotBlank(msg)) {// 对应200,表明接口请求是成功的,但是触发业务异常错误码exchange.getResponse().setStatusCode(HttpStatus.OK);return exchange.getResponse().writeWith(Flux.just(exchange.getResponse().bufferFactory().wrap(JSON.toJSONString(msg).getBytes())));
}

调试结果,右上角的Status变成200:
在这里插入图片描述
注意看,Postman可以返回中文msg。

发布测试环境后,在Chrome浏览器里却发现返回数据乱码!?
在这里插入图片描述
IDEA调整截图如上没有乱码问题,console控制台打印也是正常:
在这里插入图片描述
乱码不是什么大问题,研发这么多年遇到无数次。继续排查,做如下调整解决问题:

return exchange.getResponse().writeWith(Flux.just(exchange.getResponse().bufferFactory().wrap(JSON.toJSONString(msg).getBytes(StandardCharsets.UTF_8))));

获取请求体

前面提到,我们的App有几个功能模块,其中一个模块的请求全部dialog/nextQuestion接口。用户恶意刷数据,多次请求此接口就会触发黑名单。但是在我们的交互设计上,又希望用户从其他功能模块切换到此功能时,可以请求一次此接口。那怎么判断是第一次呢?那就需要解析requestBody。

根据下面的参考1文章,增加如下代码:

public String resolveBodyForDialog(ServerHttpRequest serverHttpRequest) {String uri = serverHttpRequest.getURI().getPath();// 只有某些请求才解析if (!StringUtils.equalsAnyIgnoreCase(uri, "dialog/nextQuestion")) {return "";}StringBuilder sb = new StringBuilder();Flux<DataBuffer> body = serverHttpRequest.getBody();body.subscribe(buffer -> {byte[] bytes = new byte[buffer.readableByteCount()];buffer.read(bytes);DataBufferUtils.release(buffer);String bodyString = new String(bytes, StandardCharsets.UTF_8);sb.append(bodyString);});return sb.toString();
}

本地调试时没有问题,可以获取到requestBody:
在这里插入图片描述
但是测试环境却又问题:
在这里插入图片描述
详细的错误日志:

500 Server Error for HTTP POST "/api/open/dialog/nextQuestion"
io.netty.handler.codec.EncoderException: io.netty.util.IllegalReferenceCountException: refCnt: 0, decrement: 1
at io.netty.handler.codec.MessageToMessageEncoder.write(MessageToMessageEncoder.java:107)
at io.netty.channel.CombinedChannelDuplexHandler.write(CombinedChannelDuplexHandler.java:348)
at io.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:716)
at io.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:708)
at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:791)
at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:701)
at reactor.netty.channel.MonoSendMany$SendManyInner.run(MonoSendMany.java:286)
at reactor.netty.channel.MonoSendMany$SendManyInner.trySchedule(MonoSendMany.java:368)
at reactor.netty.channel.MonoSendMany$SendManyInner.onSubscribe(MonoSendMany.java:221)
at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onSubscribe(FluxMapFuseable.java:90)
at reactor.core.publisher.FluxContextStart$ContextStartSubscriber.onSubscribe(FluxContextStart.java:97)
at reactor.core.publisher.MonoJust.subscribe(MonoJust.java:54)
at reactor.core.publisher.MonoSubscriberContext.subscribe(MonoSubscriberContext.java:47)
at reactor.core.publisher.FluxSourceMonoFuseable.subscribe(FluxSourceMonoFuseable.java:38)
at reactor.core.publisher.FluxMapFuseable.subscribe(FluxMapFuseable.java:63)
at reactor.core.publisher.Flux.subscribe(Flux.java:7921)
at reactor.netty.channel.MonoSendMany.subscribe(MonoSendMany.java:81)
at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.drain(MonoIgnoreThen.java:153)
at reactor.core.publisher.MonoIgnoreThen.subscribe(MonoIgnoreThen.java:56)
at reactor.core.publisher.Mono.subscribe(Mono.java:3848)
at reactor.netty.NettyOutbound.subscribe(NettyOutbound.java:305)
at reactor.core.publisher.MonoSource.subscribe(MonoSource.java:51)
at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)
at reactor.netty.http.client.HttpClientConnect$HttpIOHandlerObserver.onStateChange(HttpClientConnect.java:441)
at reactor.netty.ReactorNetty$CompositeConnectionObserver.onStateChange(ReactorNetty.java:470)
at reactor.netty.resources.PooledConnectionProvider$DisposableAcquire.onStateChange(PooledConnectionProvider.java:512)
at reactor.netty.resources.PooledConnectionProvider$PooledConnection.onStateChange(PooledConnectionProvider.java:451)
at reactor.netty.channel.ChannelOperationsHandler.channelActive(ChannelOperationsHandler.java:62)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:225)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:211)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:204)
at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelActive(CombinedChannelDuplexHandler.java:414)
at io.netty.channel.ChannelInboundHandlerAdapter.channelActive(ChannelInboundHandlerAdapter.java:69)
at io.netty.channel.CombinedChannelDuplexHandler.channelActive(CombinedChannelDuplexHandler.java:213)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:225)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:211)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:204)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelActive(DefaultChannelPipeline.java:1396)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:225)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:211)
at io.netty.channel.DefaultChannelPipeline.fireChannelActive(DefaultChannelPipeline.java:906)
at io.netty.channel.epoll.AbstractEpollChannel$AbstractEpollUnsafe.fulfillConnectPromise(AbstractEpollChannel.java:618)
at io.netty.channel.epoll.AbstractEpollChannel$AbstractEpollUnsafe.finishConnect(AbstractEpollChannel.java:651)
at io.netty.channel.epoll.AbstractEpollChannel$AbstractEpollUnsafe.epollOutReady(AbstractEpollChannel.java:527)
at io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:422)
at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:333)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:906)
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)

具体研究这篇文章,做如下调整:

String uri = serverHttpRequest.getURI().getPath();
// 只有某些请求才解析
if (!StringUtils.equalsAnyIgnoreCase(uri, DIALOG_URI)) {return "";
}
Flux<DataBuffer> body = serverHttpRequest.getBody();
AtomicReference<String> bodyRef = new AtomicReference<>();
body.subscribe(buffer -> {CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());bodyRef.set(charBuffer.toString());
});
return bodyRef.get();

上面的报错消失。问题虽然是解决,但是不明就里。

后面又发现一个乱码问题,针对如下requestBody:

{"stateId": "DASHBOARD","answer": {"transitionId": "GET_HEALTH_ADVICE","label": "开始评估症状"}
}

bodyRef.get()获取到的中文数据乱码。参考3,解决方法:

String encoding = System.getProperty("file.encoding");
CharBuffer charBuffer = Charset.forName(encoding).decode(buffer.asByteBuffer());
bodyRef.set(charBuffer.toString());

参考

  • Spring Cloud Gateway读取RequestBody数据
  • 使用Spring Cloud-Gateway WebFlux抛出指定错误代码和信息
  • 从String获得ByteBuffer、从ByteBuffer获得CharBuffer的正确姿势

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/89645.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Aruba CX交换机 VSF配置

目前 Aruba CX 交换机中的 6300F 和 6300M 支持 VSF 功能&#xff0c;要求同型号堆叠。 6300 交换机仅仅最后 4 个 SFP56 端口支持 VSF link 6200F : all uplink ports with 10G speed can be configured as VSF link 6200F: VSF allows stacks to be formed using any combin…

【C语言】快速排序

文章目录 一、hoare版本二、挖坑法三、前后指针法四、非递归快排五、快速排序优化1、三数取中选key值2、小区间优化 六、代码测试 一、hoare版本 快速排序是Hoare于1962年提出的一种二叉树结构的交换排序方法&#xff0c;其基本思想为&#xff1a;任取待排序元素序列中的某元素…

蓝桥杯每日一题2023.9.27

4408. 李白打酒加强版 - AcWing题库 题目描述 题目分析 对于这题我们发现有三个变量&#xff0c;店&#xff0c;花&#xff0c;酒的数量&#xff0c;对于这种范围我们使用DP来进行分析。 dp[i][j][k]我们表示有i个店&#xff0c;j朵花&#xff0c;k单位酒的集合&#xff0c…

信息化发展56

数据开发利用 通过数据集成、数据挖掘和数据服务&#xff08;目录服务、查询服务、浏览和下载服务、数据分发服务&#xff09;、数据可视化、信息检索等技术手段&#xff0c; 帮助数据用户从数据资源中找到所需要的数据&#xff0c; 并将数据以一定的方式展现出来&#xff0c;…

Databend 源码阅读:配置管理

作者&#xff1a;尚卓燃&#xff08;PsiACE&#xff09;澳门科技大学在读硕士&#xff0c;Databend 研发工程师实习生 Apache OpenDAL(Incubating) Committer https://github.com/PsiACE 对于 Databend 这样复杂的数据库服务端程序&#xff0c;往往需要支持大量的可配置选项&am…

PTA程序辅助实验平台——2023年软件设计综合实践_3(分支与循环)

第一题&#xff1a;7-1 印第安男孩 - C/C 分支与循环 朵拉编程的时候也想顺便练习英语。她编程从键盘读入一个整数n&#xff0c;如果n值为0或者1&#xff0c;向屏幕输出“0 indian boy.”或“1 indian boy.”&#xff1b;如果n大于1&#xff0c;比如9&#xff0c;则输出“9 in…

查看Linux系统信息的常用命令

文章目录 1. 机器配置查看2. 常用分析工具3. 常用指令解读3.1 lscpu 4. 定位僵尸进程5. 参考 1. 机器配置查看 # 总核数物理CPU个数x每颗物理CPU的核数 # 总逻辑CPU数物理CPU个数x每颗物理CPU的核数x超线程数 cat /proc/cpuinfo| grep "physical id"| sort| uniq| w…

Jmeter接口自动化和Python接口自动化,如何选择?

选择Jmeter或Python进行接口自动化测试取决于您的具体需求和环境。以下是一些可以考虑的因素&#xff1a; 1. 语言熟悉度&#xff1a;如果您对Java更熟悉&#xff0c;那么Jmeter可能是更好的选择。而如果您的团队或个人对Python更熟悉&#xff0c;那么Python可能是更好的选择。…

Python数据分析之Excel

Openpyxl库 1、Openpyxl模块2、Excel写入2.1、新建2.2、添加数据2.3、单元格格式 3、Excel读取4、Excel的CRUD4.1、查4.2、改4.3、删 1、Openpyxl模块 Openpyxl是一个用于处理xlsx格式Excel表格文件的第三方python库&#xff0c;几乎支持Excel表格的所有操作 基本概念&#x…

GaussDB数据库SQL系列-游标管理

目录 一、前言 二、概述&#xff08;GaussDB&#xff09; 1、游标概述 2、游标的使用分类 三、GaussDB中的显式游标&#xff08;示例&#xff09; 1、显式游标的使用与操作步骤 2、显式游标示例 四、GaussDB中的隐式游标&#xff08;示例&#xff09; 1、隐式游标简介…

MySQL基础进阶

文章目录 MySQL基础进阶 约束 \color{red}{约束} 约束约束的概念和分类约束的概念约束的分类 非空约束概念语法 唯一约束概念语法 主键约束概念语法 数据库设计 \color{red}{数据库设计} 数据库设计软件的研发步骤数据库设计概念数据库设计的步骤表关系一对一一对多&#xff08…

Pytest+Allure+Excel接口自动化测试框架实战

1. Allure 简介 简介 Allure 框架是一个灵活的、轻量级的、支持多语言的测试报告工具&#xff0c;它不仅以 Web 的方式展示了简介的测试结果&#xff0c;而且允许参与开发过程的每个人可以从日常执行的测试中&#xff0c;最大限度地提取有用信息。 Allure 是由 Java 语言开发的…

docker系列文章目录

docker系列专栏笔记总算完成了&#xff0c;平时下班比较晚&#xff0c;利用晚上的一些时间整理了这一系列的学习笔记。 docker系列教程包含以下几个方面&#xff1a; docker环境篇 介绍docker环境的搭建&#xff0c;已经管理平台工具(portainer)的简单使用。 docker常用命令篇…

结构型设计模式——桥接模式

摘要 桥接模式(Bridge pattern): 使用桥接模式通过将实现和抽象放在两个不同的类层次中而使它们可以独立改变。 一、桥接模式的意图 将抽象与实现分离开来&#xff0c;使它们可以独立变化。 二、桥接模式的类图 Abstraction: 定义抽象类的接口Implementor: 定义实现类接口 …

MySQL 的 C 语言接口

1. mysql_init MYSQL *mysql_init(MYSQL *mysql); mysql_init函数的作用&#xff1a;创建一个 MYSQL 对象&#xff08;该对象用于连接数据库&#xff09;。 mysql_init函数的参数&#xff1a; ① mysql&#xff1a;MYSQL 结构体指针&#xff0c;一般设置为 NULL 。 mysql_init函…

实用的 “edge://flags“

~~ edge实验室 ~~ “edge://flags” 是 Microsoft Edge 浏览器中的一个隐藏设置页面&#xff0c;允许用户启用、禁用和调整各种实验性功能和高级选项。这些功能可能会对浏览器的性能和稳定性产生影响&#xff0c;因此使用时需要谨慎。以下是一些实用的 “edge://flags” 设置…

嵌入式芯片-NE555

目录 1、比较器&#xff08;运放&#xff09; 2、相反门&#xff08;非门&#xff09; 3、或非门 4、双稳态触发器 5、NE555功能框图 1、比较器&#xff08;运放&#xff09; 2、相反门&#xff08;非门&#xff09; 3、或非门 4、双稳态触发器 5、NE555功能框图

俞敏洪:董宇辉在北京有房子了!

据媒体报道&#xff0c;9月26日&#xff0c;俞敏洪在直播中透露&#xff0c;董宇辉已经在北京拥有了自己的房子&#xff0c;并且强调这是大家共同努力的结果。 这一消息引起了广泛关注和热议。在此之前&#xff0c;董宇辉曾在公开场合表示&#xff0c;俞敏洪老师为了给他凑钱买…

数据库索引失效

索引失效是指数据库查询在执行过程中无法有效利用索引&#xff0c;导致查询性能下降或索引无法被使用的情况&#xff0c;以下是常见的导致索引失效的原因&#xff1a; 模糊查询以通配符开头&#xff0c;自己都不知道具体要查什么&#xff0c;怎么使用索引呢&#xff0c;所以会导…

输送机使用的常见误区

输送机也称流水线&#xff0c;是指在自动化生产过程中起到运输货物&#xff0c;联通各个生产设备的主要机械设备。但在使用的过程中&#xff0c;很多用户对于输送机的使用存在一定的误区&#xff0c;导致设备故障频出&#xff0c;下面就针对用户已在使用输送机过程中的常见误区…