使用Spring从服务层启动新线程的正确方法

Jan*_*eXQ 5 java service spring multithreading

我有一种很少被调用的方法。此方法在db中收集垃圾。我不想让用户等待服务器响应,因此我决定从服务层的新线程中调用此方法。我正在使用Spring。服务等级:

@Service
@Transactional
public class UploadService {

    @Resource(name = "UploadDAO")
    private UploadDao uploadDao;
Run Code Online (Sandbox Code Playgroud)

我不想等待的方法

public void collectBlobGarbage(){
        Thread th = new Thread(new Runnable() {
            @Override
            public void run() {
                uploadDao.collectBlobGarbage();
            }
        });
        th.start();
    }
Run Code Online (Sandbox Code Playgroud)

这是个好方法吗?

Tur*_*lin 8

如果您在类路径上使用Spring,则最好使用@Async

@Async
public CompletableFuture<Void> collectBlobGarbage() throws InterruptedException {
    CompletableFuture.completeFuture(uploadDao.collectBlobGarbage());
}
Run Code Online (Sandbox Code Playgroud)

在主类上,您需要使用@EnableAsync类似:

@SpringBootApplication
@EnableAsync
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
Run Code Online (Sandbox Code Playgroud)

并且您需要一个执行者bean:

@Bean
public Executor asyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setMaxPoolSize(2);
    executor.setQueueCapacity(500);
    executor.setThreadNamePrefix("Stackoverflow-");
    executor.initialize();
    return executor;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果有帮助,请考虑投票并接受答案。 (2认同)