我有一个很少被调用的方法.此方法在db中收集垃圾.我不想让用户等待服务器响应,所以我决定从我的服务层的新线程调用此方法.我正在使用Spring.
服务类:
@Service
@Transactional
public class UploadService {
@Resource(name = "UploadDAO")
private UploadDao uploadDao;
我不想等待的方法
public void collectBlobGarbage(){
Thread th = new Thread(new Runnable() {
@Override
public void run() {
uploadDao.collectBlobGarbage();
}
});
th.start();
}
是这样做的好方法吗?
解决方法:
如果你的类路径上有Spring,那么你也可以使用@Async
@Async
public CompletableFuture collectBlobGarbage() throws InterruptedException {
CompletableFuture.completeFuture(uploadDao.collectBlobGarbage());
}
在您的主类上,您需要使用@EnableAsync,如:
@SpringBootApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
而且你需要一个执行者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;
}
标签:java,multithreading,spring,service
来源: https://codeday.me/bug/20190622/1263869.html