在非同步任務執行中啟用請求範圍
問題:
解決方案:
為了在非同步任務執行中啟用請求作用域,創建了一個自定義的TaskPoolExecutor以及一個特殊的Callable,用於存儲和清除後台線程的請求上下文。實作:
自訂執行器:
<code class="java">public class ContextAwarePoolExecutor extends ThreadPoolTaskExecutor { @Override public <T> Future<T> submit(Callable<T> task) { return super.submit(new ContextAwareCallable(task, RequestContextHolder.currentRequestAttributes())); } }</code>
上下文感知可調用:
<code class="java">public class ContextAwareCallable<T> implements Callable<T> { private Callable<T> task; private RequestAttributes context; public ContextAwareCallable(Callable<T> task, RequestAttributes context) { this.task = task; this.context = context; } @Override public T call() throws Exception { if (context != null) { RequestContextHolder.setRequestAttributes(context); } try { return task.call(); } finally { RequestContextHolder.resetRequestAttributes(); } } }</code>
<code class="java">@Configuration public class ExecutorConfig extends AsyncConfigurerSupport { @Override @Bean public Executor getAsyncExecutor() { return new ContextAwarePoolExecutor(); } }</code>
<code class="java">taskExecutor.execute(new ContextAwareCallable(new Runnable() { @Override public void run() { asyncRequest(request); } }), RequestContextHolder.currentRequestAttributes());</code>
此方法僅支援請求和會話範圍,不支援安全上下文。
以上是如何在非同步任務執行中啟用請求範圍?的詳細內容。更多資訊請關注PHP中文網其他相關文章!