簡體   English   中英

在Spring Web服務中創建新線程

[英]Creating a new thread in a Spring webservice

我目前正在維護一個大型Spring MVC應用程序,該應用程序位於大型企業Java應用程序之上。 我所在地區的Spring MVC的目的是顯示以支持應用程序的當前狀態-它通過對應用程序的各個不同模塊進行運行狀況檢查來實現此目的。

我當前要為此設置超時,方法是在單獨的線程中啟動運行狀況測試,並使用ExecutorService進行計時,並在線程花費的時間長於x秒的情況下將其終止。 我遵循了這個極好的答案,並將HealthCheckRunner (接受HealthCheck )封裝到一個Runnable類中,我將其稱為HealthCheckWorker 當前的實現如下所示:

                        HealthCheckWorker hcw = new HealthCheckWorker(healthCheck,runner);
                        Thread thread = new Thread(hcw);

                        final ExecutorService executor = Executors.newSingleThreadExecutor();
                        final Future future = executor.submit(thread);
                        executor.shutdown(); 
                        future.get(60, TimeUnit.SECONDS);

但是,我得到了一個java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request. java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request. 錯誤。 我該如何解決?

使用@Async 您將獲得具有cancel方法的Future

根據您的問題,這里是如何實現這一目標

@Configuration
public class ListenerConfig {

    @Bean
    public RequestContextFilter requestContextFilter() {
        RequestContextFilter requestContextFilter = new RequestContextFilter();
        requestContextFilter.setThreadContextInheritable(true);
        return requestContextFilter;
    }
}

正確回答這個問題是非常復雜的。 我的第一個建議是,如果您想使用一些與Web線程相關的數據更正確,請采用此數據並針對Web上下文構建healt服務作為松散的復制服務,以便根據需要進行擴展。 如果您可以通過多種選擇來設計HealthChecker,則可以在網關上使用帶有超時的Spring Integration管道,將消息系統用作ActiveMq,Rabit等,或將multithead方法用作在您的問題中,但重點是,如果熱聊天的過程很復雜,因為我不知道您是否必須聚合來自更多數據源的某些數據或像這樣收集數據,但是如果您的服務被隔離到僅擁有的數據上在您的Web請求的本地,您應該不會遇到像您這樣的問題,並且您可以受益於多種選擇來擴展您的服務

我希望這種思考可以幫助您找到解決方案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM