簡體   English   中英

在 grpc Spring 引導中關閉自定義線程池執行程序

[英]Shutting down Custom Thread Pool executor in grpc Spring boot

我正在創建一個應用程序,我在其中使用 Spring Boot 來構建 gRPC 客戶端和服務器。 我有一個要求,我想在 9 小時后關閉我的服務。 第二天又開始了。 對於 grpc Server,提供了一個默認的線程池,但是我們可以通過調用serverBuilder.executor(our custom executor)來提供我們自己的自定義線程池,但是當我們提供自定義的 executor 時,關閉它就成了我們的責任。

現在,如果我們不使用 Spring Boot,我們可以在我們用來終止服務的自定義方法中調用 shutDown()/shutDownNow()。

但是當我們使用 Spring Boot 時,我們提供了這樣的自定義執行器

@Component
public class BootGrpcConfiguration extends GRpcServerBuilderConfigurer{

    @Override
    public void configure(ServerBuilder<?> serverBuilder) {
        ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(1);
        serverBuilder.executor(threadPoolExecutor);

    }

}

現在要關閉它,有多種可能的方法:

  1. 在配置方法本身中使用 awaitTermination(9, TimeUnit.HOURS)
  2. 讓我的 cutom execuotr 成為一個 bean 並從代碼中的任何位置關閉它
  3. 從方法中聲明 ExecutorService threadPoolExecutor 實例並使用某種 getter 來獲取它,然后從代碼中的任何位置對其調用 shutdowndDown 方法。

你認為哪種方式更有效率? 特別是我想問一下,將自定義執行器設為 bean 是否是個好主意?

您需要告訴 spring 當您的組件被銷毀時該怎么做,例如:

@Component
public class BootGrpcConfiguration extends GRpcServerBuilderConfigurer{

    private ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(1);

    @Override
    public void configure(ServerBuilder<?> serverBuilder) {
        serverBuilder.executor(threadPoolExecutor);

    }

    @PreDestroy
    public void destroy() {
        threadPoolExecutor.shutdown();
    }

}

如果將線程池創建為 bean,則可以在其中聲明 destroy 方法:

@Configuration
public class AppConfiguration {

    @Bean(destroyMethod = "shutdown")
    public ExecutorService initializeExecutorService() {
        return Executors.newFixedThreadPool(1);
    }
}

您當然需要一個在一段時間內不接受新工作的自定義執行程序:

ExecutorService executorService = new ThreadPoolExecutor() {

    @Override   
    protected void beforeExecute(Thread t, Runnable r) {
        super.beforeExecute(t, r);
        // do some checks here
    }
 }

暫無
暫無

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

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