3 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超5個(gè)贊
我通過為我的可運(yùn)行對(duì)象擴(kuò)展 ConcurrentLinkedQueue 并將它們保存在我在 ServletContextListener 的 initialize 方法中實(shí)例化的管理器中解決了這個(gè)解決方案。通過覆蓋 ConcurrentLinkedQueue 的 offer() 方法來持續(xù)輪詢直到隊(duì)列為空,我能夠同步處理可運(yùn)行對(duì)象。
不幸的是,這會(huì)鎖定請(qǐng)求線程,直到 runnable 完成,我將不得不讓我的用戶密切關(guān)注它并讓我知道頁面是否最終運(yùn)行很長(zhǎng)時(shí)間,但至少在我的測(cè)試環(huán)境中,該過程似乎是亞秒即使我一次打 20 個(gè),所以我現(xiàn)在還好。
我仍然更喜歡從我的 Tomcat 容器執(zhí)行的 ExecutorService 但在請(qǐng)求范圍之外,但除非有人可以回答這個(gè)問題,否則我現(xiàn)在只好離開它

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊
“我相信有更好的方法可以做到這一點(diǎn)”
基于此,您需要在調(diào)用另一個(gè)線程之前創(chuàng)建/查找所有請(qǐng)求和會(huì)話范圍的組件。實(shí)際上,請(qǐng)求注入是線程本地的,無法在您的場(chǎng)景中工作。

TA貢獻(xiàn)2021條經(jīng)驗(yàn) 獲得超8個(gè)贊
你看起來像那樣嗎?
@Component 公共類 AsynchronousThread 擴(kuò)展了 Thread {
public static final Logger LOGGER = LoggerFactory
.getLogger(AsynchronousThread.class);
@Autowired
private Writer writer;
private BlockingQueue<IndexContextDTO> blockingQueue = new LinkedBlockingQueue<IndexContextDTO>(
500);
/**
*
*/
public AsynchronousThread() {
super("AsynchronousThread");
}
@PostConstruct
public void init() {
Integer internalQueueSize = 100;
this.blockingQueue = new LinkedBlockingQueue<>(internalQueueSize);
this.start();
}
@Override
public void run() {
while (true) {
// Do stuff
}
}
public void putInQueue(IndexContextDTO message) {
try {
this.blockingQueue.put(message);
} catch (InterruptedException interruptedException) {
// This exception will be thrown in very rare case.
LOGGER.error("An error while putting message in the queue. "
+ message, interruptedException);
}
}
}
添加回答
舉報(bào)