前言 在使用框架日常開發中需要在controller中進行一些非同步操作減少請求時間,但是發現在使用@Anysc註解後會出現Request對象無法獲取的情況,本文就此情況給出完整的解決方案 原因分析 @Anysc註解會開啟一個新的線程,主線程的Request和子線程是不共用的,所以獲取為null 在使 ...
前言
在使用框架日常開發中需要在controller中進行一些非同步操作減少請求時間,但是發現在使用@Anysc註解後會出現Request對象無法獲取的情況,本文就此情況給出完整的解決方案
原因分析
- @Anysc註解會開啟一個新的線程,主線程的Request和子線程是不共用的,所以獲取為null
- 在使用springboot的自定帶的線程共用後,代碼如下,Request不為null,但是偶發的其中body/head/urlparam內容出現獲取不到的情況,是因為非同步任務在未執行完畢的情況下,主線程已經返回,拷貝共用的Request對象數據被清空
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//設置子線程共用
RequestContextHolder.setRequestAttributes(servletRequestAttributes, true);
HttpServletRequest request = servletRequestAttributes.getRequest();
解決方案
前置條件
-
啟動類添加@EnableAsync註解
-
標記@Async的非同步方法不能和調用者在同一個class中
pom配置
<!-- 阿裡線程共用 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>transmittable-thread-local</artifactId>
<version>2.11.0</version>
</dependency>
requrest共用
通過TransmittableThreadLocal對象進行線程對象共用
public class CommonUtil {
public static TransmittableThreadLocal<HttpServletRequest> requestTransmittableThreadLocal = new TransmittableThreadLocal<HttpServletRequest>();
public static void shareRequest(HttpServletRequest request){
requestTransmittableThreadLocal.set(request);
}
public static HttpServletRequest getRequest(){
HttpServletRequest request = requestTransmittableThreadLocal.get();
if(request!=null){
return requestTransmittableThreadLocal.get();
}else{
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if(requestAttributes!=null){
return requestAttributes.getRequest();
}else{
return null;
}
}
}
public static void remove(){
requestTransmittableThreadLocal.remove();
}
}
註:系統中所有Request獲取需要統一從CommonUtil指定來源,例如token鑒權等
自定義request過濾器
通過自定義過濾器對Request的內容進行備份保存,主線程結束時Request清除結束不會影響到子線程的相應參數的獲取,也適用於增加攔截器/過濾器後body參數無法重覆獲取的問題。需要註意的是對header參數處理時key要忽略大小寫
public class HttpServletRequestReplacedFilter implements Filter, Ordered {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
ServletRequest requestWrapper = null;
if (request instanceof HttpServletRequest) {
requestWrapper = new RequestWrapper((HttpServletRequest) request);
}
//獲取請求中的流如何,將取出來的字元串,再次轉換成流,然後把它放入到新request對象中。
// 在chain.doFiler方法中傳遞新的request對象
if (requestWrapper == null) {
chain.doFilter(request, response);
} else {
chain.doFilter(requestWrapper, response);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
@Override
public int getOrder() {
return 10;
}
}
public class RequestWrapper extends HttpServletRequestWrapper{
private final byte[] body;
private final HashMap<String,String> headMap;
private final HashMap<String,String> requestParamMap;
public RequestWrapper(HttpServletRequest request) throws IOException {
super(request);
body = CommonUtil.getBodyString(request).getBytes(Charset.forName("UTF-8"));
headMap = new HashMap();
Enumeration<String> headNameList = request.getHeaderNames();
while (headNameList.hasMoreElements()){
String key = headNameList.nextElement();
headMap.put(key.toLowerCase(),request.getHeader(key));
}
requestParamMap = new HashMap<>();
Enumeration<String> parameterNameList = request.getParameterNames();
while (parameterNameList.hasMoreElements()){
String key = parameterNameList.nextElement();
requestParamMap.put(key,request.getParameter(key));
}
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public int read() throws IOException {
return bais.read();
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
};
}
@Override
public String getHeader(String name) {
return headMap.get(name.toLowerCase());
}
@Override
public String getParameter(String name) {
return requestParamMap.get(name);
}
}
自定義任務執行器
用於攔截非同步任務執行,在任務執前統一進行Request共用操作,且可以定義多個,不影響原有的非同步任務代碼
public class CustomTaskDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable runnable) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
System.out.println("非同步任務共用request");
return () -> {
try {
CommonUtil.shareRequest(request);
runnable.run();
} finally {
CommonUtil.remove();
}
};
}
}
@Configuration
public class TaskExecutorConfig {
@Bean()
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(200);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("taskExecutor-");
executor.setAwaitTerminationSeconds(60);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
@Bean("shareTaskExecutor")
public Executor hpTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(200);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("shareTaskExecutor-");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
// 增加 TaskDecorator 屬性的配置
executor.setTaskDecorator(new CustomTaskDecorator());
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
調用示例
給@Anysc註解指定進行共用攔截的任務執行器即可
@PostMapping("/testAsync")
@ResponseBody
public Object testAsync(@RequestBody Map<String, Object> params) throws Exception{
Result result = Result.okResult();
asyncUtil.executeAsync();
return result;
}
@Component
public class AsyncUtil {
@Async("shareTaskExecutor")
public void executeAsync () throws InterruptedException {
System.out.println("開始執行executeAsync");
Thread.sleep(3000);
System.out.println("結束執行executeAsync");
}
}