一次诡异405 METHOD_NOT_ALLOWED “Request method ‘POST‘ not supported“问题排查记录

概述

任何稍微只要有一点经验的开发者都知道HTTP 405,表示方法不支持。如,本来是定义为POST接口,前端使用GET请求,就会报错。

但是我还真遇上一次405 METHOD_NOT_ALLOWED "Request method 'POST' not supported"问题,并且是在开发7年后,看得我一脸懵逼。本文记录一下。

问题

背景:使用微服务开发模式后,几乎所有服务都是走gateway网关。

某次常规回归测试,发现生产环境的小程序不可用。请求会经过网关鉴权、路由,于是去查找网关服务的报错日志:

gateway-d | [reactor-http-epoll-4] |  | WARN  | com.aba.gateway.exception.JsonErrorWebExceptionHandler | getErrorAttributes | 38 | - 网关异常,path:/api/dx/user/login/mini-program,method:POST,message:405 METHOD_NOT_ALLOWED "Request method 'POST' not supported"
at org.springframework.web.reactive.result.method.RequestMappingInfoHandlerMapping.handleNoMatch(RequestMappingInfoHandlerMapping.java:163)
	at org.springframework.web.reactive.result.method.AbstractHandlerMethodMapping.lookupHandlerMethod(AbstractHandlerMethodMapping.java:344)
	at org.springframework.web.reactive.result.method.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:292)
	at org.springframework.web.reactive.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:174)

报错网关服务代码片段,注意下面标记的报错行:

import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;

@Slf4j
public class JsonErrorWebExceptionHandler extends DefaultErrorWebExceptionHandler {
    
    

    public JsonErrorWebExceptionHandler(ErrorAttributes errorAttributes,
                                        ResourceProperties resourceProperties,
                                        ErrorProperties errorProperties,
                                        ApplicationContext applicationContext) {
    
    
        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
    }

    @Override
    protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
    
    
        // 这里其实可以根据异常类型进行定制化逻辑
        Throwable error = super.getError(request);
        Map<String, Object> errorAttributes = new HashMap<>(8);
        errorAttributes.put("message", error.getMessage());
        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;
    }

    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
    
    
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    @Override
    protected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {
    
    
        // 这里其实可以根据errorAttributes里面的属性定制HTTP响应码
        return HttpStatus.INTERNAL_SERVER_ERROR;
    }
}

配置类:

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.config.WebFluxConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

@Slf4j
@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@ConditionalOnClass(WebFluxConfigurer.class)
@AutoConfigureBefore(WebFluxAutoConfiguration.class)
@EnableConfigurationProperties({
    
    ServerProperties.class, ResourceProperties.class})
public class CustomErrorAutoConfiguration {
    
    

    private final ServerProperties serverProperties;
    private final ApplicationContext applicationContext;
    private final ResourceProperties resourceProperties;
    private final List<ViewResolver> viewResolvers;
    private final ServerCodecConfigurer serverCodecConfigurer;

    public CustomErrorAutoConfiguration(ServerProperties serverProperties,
                                        ResourceProperties resourceProperties,
                                        ObjectProvider<ViewResolver> viewResolversProvider,
                                        ServerCodecConfigurer serverCodecConfigurer,
                                        ApplicationContext applicationContext) {
    
    
        this.serverProperties = serverProperties;
        this.applicationContext = applicationContext;
        this.resourceProperties = resourceProperties;
        this.viewResolvers = viewResolversProvider.orderedStream()
                .collect(Collectors.toList());
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    @Bean
    @ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
    public DefaultErrorAttributes errorAttributes() {
    
    
        return new DefaultErrorAttributes(this.serverProperties.getError().isIncludeException());
    }

    @Bean
    @ConditionalOnMissingBean(value = ErrorWebExceptionHandler.class, search = SearchStrategy.CURRENT)
    @Order(-1)
    public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) {
    
    
        JsonErrorWebExceptionHandler exceptionHandler = new JsonErrorWebExceptionHandler(
                errorAttributes,
                resourceProperties,
                this.serverProperties.getError(),
                applicationContext);
        exceptionHandler.setViewResolvers(this.viewResolvers);
        exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());
        exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());
        return exceptionHandler;
    }
}

上面两个类的代码,看不出什么问题,至此仍旧是一脸懵逼。Google肯定是不可能给出满意的答案的,它只会让你去检查前端请求的方法是否正确。

前端和后端肯定都没有动过小程序登录接口/api/dx/user/login/mini-program相关代码,后端此接口在另一个服务:

/**
 * 微信小程序登录
 */
@PostMapping({
    
    "/login/mini-program"})
@ApiOperation(value = "微信小程序登录", produces = "application/json", consumes = "application/json")
public AdaResponse<BaseLoginVo> miniProgram(@RequestBody UserSocialParam userSocialParam) {
    
    
}

排查

前端和后端都没有改过登录接口,那就只能从gateway网关服务下手。值得一提的是,排查思路很重要,如果把精力放在Google,或者排查服务提供者应用(而不是网关)上,就会浪费精力,增加生产问题影响面。

另外,出现生产问题时,如果可以回滚(不会影响生产环境的数据等),则应该尽快回滚之前的版本。看一下之前的版本是否还有此问题。没有问题,则大吉大利,可以对比两个版本之前的修改记录和区别。

至于回滚哪个服务,还是要根据业务架构设计,服务之间的依赖关系,及最近的发布变更等因素,来分析。

复现

排查问题时,如果能本地复现,比盲目Google强太多。好在本地可以复现问题:
在这里插入图片描述
可以复现问题,还是上面的代码片段,看不出问题,又要怎么解决问题呢?

对比

测试环境里,小程序登录接口正常!那就对比测试和生产环境的代码版本!!

打开Rancher,找到测试环境和生产环境分别使用的版本。

打开GitLab,对比两个版本有啥区别:
在这里插入图片描述
右侧的Target选择被对比的版本,也可以是Branch、Tag等。左侧的Source是相对于Target版本,新增的提交commit信息。看一下GitLab URL,其格式如:/compare/Target...Source
在这里插入图片描述
点击上面截图里左侧的Swap revisions,可快速切换Source和Target。
在这里插入图片描述
总之,git commit提交信息不多,完全看不出哪次提交有问题。那就把本地代码恢复到测试环境的版本。执行命令:git checkout stg20201125v01
在这里插入图片描述
Debug模式启动应用,上面报错的方法,断点还是打开状态,gatew网关并没有走到此方法,也就是说本地代码回滚版本后,不再抛异常。

请求从gateway正常转发到enduser-dx服务!!打印日志如下:

2023-06-01 18:50:26 |  | 10.18.66.118 | 51651 | enduser-provider-dx | [http-nio-8199-exec-9] |  | INFO  | com.aba.enduser.dx.aop.LogAspect | log | 40 | - 请求开始, com.aba.enduser.dx.controller.LoginController#miniProgram() URI: /api/dx/user/login/mini-program, method: POST, URL: http://10.18.66.118:8199/api/dx/user/login/mini-program, params: null

我靠!!

结论:GitLab 对比得出的几次提交,/compare/Target...Source,某个地方的改动引发此问题。

逐个撤销回滚上面几次提交的改动,最终定位到gatew网关服务新增的如下代码引发问题:

@RestController
public class HealthController {
    
    
    @GetMapping({
    
    "/health/check"})
    public String heathCheck() {
    
    
        return "OK";
    }

	// 引发问题
    @GetMapping()
    public String index() {
    
    
        return "index";
    }
}

把上面新增的index这个@GetMapping删除解决问题

分析

@GetMapping

为啥要新增如下代码:

@GetMapping()
public String index() {
    
    
    return "index";
}

为了减少生产环境的日志打印:

gateway-d | [reactor-http-epoll-3] |  | ERROR | o.s.b.a.web.reactive.error.AbstractErrorWebExceptionHandler | error | 122 | - [2a2e51e5] 500 Server Error for HTTP GET "/"
org.springframework.web.server.ResponseStatusException: 404 NOT_FOUND
	at org.springframework.web.reactive.resource.ResourceWebHandler.lambda$handle$0(ResourceWebHandler.java:325)
	at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:44)
	at reactor.core.publisher.Mono.subscribe(Mono.java:3848)
	at reactor.core.publisher.FluxSwitchIfEmpty$SwitchIfEmptySubscriber.onComplete(FluxSwitchIfEmpty.java:75)
	at reactor.core.publisher.Operators.complete(Operators.java:131)

生产环境正常接受前端的请求,并做鉴权和路由转发等。但是时不时总会打印如上报错信息,也不知道生产环境的某个环节(节点)的服务是否正常,不知道是不是前段的请求响应失败。

为啥405

为啥加个表示/请求路径的@GetMapping,就100%出现HTTP 405问题?另外在index()方法里面加断点,加logger,调试并没有进入此方法,console控制台也没有打印信息。

Why??不得而知。

我好菜逼啊。

参考

猜你喜欢

转载自blog.csdn.net/lonelymanontheway/article/details/131020800