一 背景
1 spring webflux应用 Controller方法参数加了@RequestParam即参数必须有,否则会报错
2 应用接口经过了zuul网关做转发
controller方法如下:
1
2
3
4
5
6 "/api/coupons/activitySimples") (value =
public Mono<List<CouponActivitySimple>> getCouponActivitySimples(
Long productCode,
String profitLevel) {
....
}
zuul网关如下:1
2
3
4
5
6
7
8zuul:
routes:
coupon-service-v2:
path: /coupon/**
url: http://【coupon-service-host】/api
sensitiveHeaders:
customSensitiveHeaders: true
addHostHeader: true
1 | curl -XGET http://【zuul-gateway-host】/coupon/coupons/activitySimples?productCode=1&profitLevel= |
二 现象
报如下异常:1
2
3
4
5
6org.springframework.web.server.ServerWebInputException: 400 BAD_REQUEST "Required String parameter 'profitLevel' is not present"
at org.springframework.web.reactive.result.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:114) ~[spring-webflux-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
at org.springframework.web.reactive.result.method.annotation.AbstractNamedValueArgumentResolver.lambda$getDefaultValue$1(AbstractNamedValueArgumentResolver.java:215) ~[spring-webflux-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
at reactor.core.publisher.MonoSupplier.subscribe(MonoSupplier.java:56) [reactor-core-3.3.0.RELEASE.jar!/:3.3.0.RELEASE]
at reactor.core.publisher.Mono.subscribe(Mono.java:4087) ~[reactor-core-3.3.0.RELEASE.jar!/:3.3.0.RELEASE]
at reactor.core.publisher.FluxSwitchIfEmpty$SwitchIfEmptySubscriber.onComplete(FluxSwitchIfEmpty.java:75...
三 原因
通过断点方式,发现通过了zuul网关之后,请求的uri变成了如下,即profitLevel后面的等于号不见了,然后从request中取出来的值是null,并非空字符串1
/coupon/coupons/activitySimples?productCode=1&profitLevel
四 解决方案
1 不使用zuul网关,用spring-cloud-gateway2.x网关,不会有如上问题
2 允许profitLevel字段为空 @RequestParam(require = false) String profitLevel