在 Spring Boot 中分配专用后台线程的最佳方法

Best approach to allocate dedicated background thread in Spring Boot

我需要创建一个监听 DatagramSocket 的专用线程。 老派方法是在上下文创建期间创建一个:

@Bean
void beanDef() {
   var thread = new Thread(myRunnable);
   thread.setDaemon(true);
   thread.start();
}

更现代的方法是创建一个执行器:

@Bean
Executor() {
   var executor = Executors.newSingleThreadExecutor();
    executor.submit(myRunnable);
}

我更喜欢哪一个?

最好使用@Async注解在后台创建线程。 @EnableAsync 注释开启 Spring 在后台线程池中执行 运行 @Async 方法的能力。这个class还自定义了使用的Executor。

@Configuration
@EnableAsync
public class ThreadConfig {
    @Bean(name = "specificTaskExecutor")
    public TaskExecutor specificTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.initialize();
        return executor;
    }
}

在下面的片段中

@Async("specificTaskExecutor")
public void runFromAnotherThreadPool() {
    System.out.println("You function code here");
}

希望对您有所帮助。

像这样的东西是在 Spring 中启动后台线程的现代方式:

@Component
public class MySocketListenerLauncher {

 private ExecutorService executorService;

 @PostConstruct
 public void init() {

  BasicThreadFactory factory = new BasicThreadFactory.Builder()
    .namingPattern("socket-listener-%d").build();

  executorService = Executors.newSingleThreadExecutor(factory);
  executorService.execute(new Runnable() {

   @Override
   public void run() {
    // ... listen to socket ...
   }
  });

  executorService.shutdown();

 }

 @PreDestroy
 public void shutdown() {
  if (executorService != null) {
   executorService.shutdownNow();
  }
 }

}