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)
这是个好方法吗?
如果您在类路径上使用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)
| 归档时间: |
|
| 查看次数: |
2609 次 |
| 最近记录: |