在grpc Spring Boot中关闭自定义线程池执行程序

安吉特:

我正在创建一个使用Spring Boot来构建gRPC客户端和服务器的应用程序。我有一个要求,我想在9小时后关闭我的服务。第二天又开始了。对于grpc Server,提供了一个默认线程池,但是我们可以通过调用来提供我们自己的自定义线程池,serverBuilder.executor(our custom 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. 在configure方法本身内部使用awaitTermination(9,TimeUnit.HOURS)
  2. 使我的cutout执行器成为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
    }
 }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

防止在Spring Boot应用程序中针对自定义异常的堆栈跟踪日志记录

在Spring Boot应用程序中重定向到自定义错误页面时出错

Rest Service中的Spring Boot自定义异常

使用自定义DiskSpaceHealthIndicator(Spring Boot执行器)?

如何在销毁Web应用程序中的所有其他bean之前关闭Spring任务执行程序/调度程序池?

Java如何在Spring Boot中增加grpc服务器的消息大小

未定义:grpc.SupportPackageIsVersion7 grpc.ServiceRegistrar

LogNet gRPC Spring Boot启动程序-解决服务而无需发现服务

Spring Boot gRPC:发生业务错误时如何返回错误代码?

使用IntelliJ在Spring Boot中自定义应用程序属性

在Spring Boot中执行计划的自定义SQL查询

在Spring Boot应用程序中创建自定义连接池

spring-boot在Java中向执行器外壳添加自定义命令

Spring Boot-Application.properties中的自定义变量

在Spring Boot中编写自定义查询

拆分服务程序gRPC python

Spring Boot执行器-实施自定义指标

配置Spring WebFlux WebClient使用自定义线程池

自定义MessageConverter在Spring Boot中不起作用

如何正确传播gRPC错误Spring-boot

如何在Spring MVC(非Spring Boot)应用程序中自定义Jackson

未定义:编译grpc时为grpc.ClientConnInterface

如何在Spring MVC中执行自定义验证?

如何使用Spring正确关闭执行程序服务?

spring-boot中的自定义404错误页面

带有自定义 fork 加入池的 Spring Boot

非常困惑: spring-boot-starter-web 是否需要使用 Spring Boot 和 gRPC

Spring Boot:请求参数中的自定义验证

等到 grpc::Server 线程退出