最近需要做一個日誌框架,針對controller 做一個Agent 切面;
在處理spring mvc 異步的時候,獲取不了他的返回值
於是參考下面博客的一篇文章,對我很有啓發
說一下,現在進程,
Tomcat Http A
Tomcat Http SyncB
Tomcat Http C
org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter.postProcess()
這個是異步線程回調的時候,執行的方法
Tomcat Http A,Tomcat Http C 他們的Request 和Reponse 是可以共用的,所以他們兩個之間通信是不存在問題
但是日誌實現是通過MDC,的線程變量實現的,所以A和B,或者B和C不能通過MDC 傳遞數據
參考以前項目的老代碼,他只通過註冊一個,CallableProcessingInterceptorAdapter子類,
通過複寫org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter.beforeConcurrentHandling()
這個方法,保存到一個臨時變量,在postProcess方法時候,再把它取出來,這個就是A,B,C的數據得到有效的傳遞
-------
說一下我的實現:
@Before(method = {"beforeConcurrentHandling"}) public void before(NativeWebRequest request, Callable<Object> task) { request.setAttribute(youFlag, id, RequestAttributes.SCOPE_REQUEST); ..... 還正在 Tomcat Http A 線程中 } @After(method = {"postProcess"}) public void after(NativeWebRequest request, Callable<Object> task, Object concurrentResult, @Thrown Throwable throwable) { String data= (String) request.getAttribute(youFlag, RequestAttributes.SCOPE_REQUEST); log(data+concurrentResult) //還正在 Tomcat Http B 線程中 }
我的借用框架是promagent,通過NativeWebRequest request,來傳遞數據,
成功解決tomcat 異步線程數據傳遞