spring - 如何在 Spring Boot 中使用异步?

标签 spring multithreading spring-boot rest asynchronous

下面是我的代码。

使用下面的代码,不会创建不同的线程 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来判断线程池是否被使用。可以设置线程前缀,通过日志判断

  1. 配置线程池
@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);
        }
    
  • 查看日志 enter image description here
  • 关于spring - 如何在 Spring Boot 中使用异步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70159140/

    相关文章:

    java - Spring 和 Angular2 400(错误请求)

    java - 如何从任何地方获取上下文?

    创建新流程并期待输出

    java - Spring Boot 2 Maven 项目在 Intellij 上运行但不在 Tomcat 上运行

    java - JUnit 用于 void 删除方法

    java - Spring 启动: Disable fetch of PersistentBag programatically

    java - 在 Maven 中配置 JUnit 目录结构

    java - 有界队列的线程池

    java - Spring 支持 MIME 类型 "multipart/byteranges"

    java - Spring-Boot 2+ 强制使用 CGLIB 代理,即使 proxyTargetClass = false