天天看點

Feign 調用過程中的一次采坑日記

1、出現的問題

在使用feign 調用過程中出現了 java.lang.NullPointerException: null 空指針錯誤,

Feign 調用過程中的一次采坑日記

根據debug 資訊可以看到是由 (ServletRequestAttributes)RequestContextHolder.getRequestAttributes()報出來的,可以看出主要是由RequestContextHolder 報出來的

估計很多人正常在使用過程中不會産生這種問題,都能正常請求到。

 2、出現的問題的原因

原因是,正常情況下,我們都在controller方法内或者後調用fegin,而我這次是在filter 中就使用了fegin調用了遠端接口,這個時候

RequestContextHolder中的RequestAttributes 還是空的,這裡面是個ThreadLocal,下面是RequestContextHolder中的部分源碼

private static final ThreadLocal<RequestAttributes> requestAttributesHolder =
			new NamedThreadLocal<RequestAttributes>("Request attributes");

	private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder =
			new NamedInheritableThreadLocal<RequestAttributes>("Request context");
           

這個原因就要去追蹤RequestContextHolder的源碼了,最終request和response等是什麼時候設定進去的? 這兒我給一個連接配接,有博友寫的還算很詳細的,有興趣的可以點進去看看https://blog.csdn.net/u012706811/article/details/53432032

3、解決辦法

在配置類中,加上 RequestContextListener監聽器的初始化,監聽http請求事件,這樣就能解決了

/**
     * 監聽器:監聽HTTP請求事件
     * 解決RequestContextHolder.getRequestAttributes()空指針問題
     * @return
     */
    @Bean
    public RequestContextListener requestContextListener(){
        return new RequestContextListener();
    }
           

額外擴充一下,開起 Feign logging 開啟調用日志

application.yml 配置

logging:
  level:
    yourproject.userClient: debug
           

在配置類或者啟動類中初始換 Logger.Level,示例給個配置類

@Configuration
public class FeignConfiguration {
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}
           

效果:

請求:

Feign 調用過程中的一次采坑日記

響應:

Feign 調用過程中的一次采坑日記

-- end