下面是我的代码。
使用下面的代码,不会创建不同的线程 ID。
输出具有相同的线程 ID。
@Controller
@RequestMapping(value = "/Main")
public class MyController
{
@Autowired
private MyService myService;
@PostMapping("/Sub")
@ResponseBody
public String readInput(@RequestBody String name)
{
for (int i = 0;i<5;i++)
{
myService.asyncMethod();
}
return "Success";
}
}
使用下面的代码,不会创建不同的线程 ID。
@Repository
@Configuration
@EnableAsync
public class MyService {
@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
return new ThreadPoolTaskExecutor();
}
@Async("threadPoolTaskExecutor")
public void asyncMethod() {
System.out.println("Thread " + Thread.currentThread().getId()+ " is running");
}
}
最佳答案
首先,无法通过线程id来判断线程池是否被使用。可以设置线程前缀,通过日志判断
- 配置线程池
@Slf4j
@Configuration
public class ThreadExecutorConfig {
@Autowired
private ThreadPoolProperties threadPoolProperties;
@Bean(name = "taskExecutor")
public ExecutorService executorService() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
executor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
executor.setQueueCapacity(threadPoolProperties.getQueueSize());
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setThreadNamePrefix("myThread-");
executor.initialize();
log.info("threadPoolConfig;corePoolSize:[{}];maxPoolSize:[{}];queueSize:[{}]",
threadPoolProperties.getCorePoolSize(),
threadPoolProperties.getMaxPoolSize(),
threadPoolProperties.getQueueSize());
return executor.getThreadPoolExecutor();
}
}
- 在方法上使用 @Async 注释
@Async(value = "taskExecutor")
@Override
public void asyncSave(OperationLogModel entity) {
if (log.isDebugEnabled()) {
log.debug("thread:{};entity:{}", Thread.currentThread().getName(), entity.toString());
}
entity.setCreateTime(LocalDateTime.now());
super.save(entity);
}
关于spring - 如何在 Spring Boot 中使用异步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70159140/