Spring中的Java线程池及异步配置

7 篇文章 0 订阅
5 篇文章 0 订阅
  1. 异步方法返回值只有两种情况,voidFuture 对象;

  2. 添加线程池配置:

    thread-pool:
      max-pool-size: 50
      core-pool-size: 20
      queue-capacity: 2000
      keep-alive-seconds: 120
    
  3. 创建配置类:

    @EnableAsync
    @Configuration
    public class AsyncConfig {
    
        /**
         * 线程池的最大池大小,默认为 Integer.MAX_VALUE
         */
        @Value("${thread-pool.max-pool-size:20}")
        private int MAX_POOL_SIZE;
    
        /**
         * 线程池的核心池大小,默认为 1
         */
        @Value("${thread-pool.core-pool-size:10}")
        private int CORE_POOL_SIZE;
    
        /**
         * 队列容量大小,默认为 Integer.MAX_VALUE
         */
        @Value("${thread-pool.queue-capacity:200}")
        private int QUEUE_CAPACITY;
    
        /**
         * 生命周期,默认为 60,单位:秒
         */
        @Value("${thread-pool.keep-alive-seconds:60}")
        private int KEEP_ALIVE_SECONDS;
    
        /**
         * 线程池
         *
         * @return asyncExecutor
         */
        @Bean(name = "asyncExecutor")
        public AsyncTaskExecutor asyncExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setMaxPoolSize(MAX_POOL_SIZE);
            executor.setCorePoolSize(CORE_POOL_SIZE);
            executor.setQueueCapacity(QUEUE_CAPACITY);
            executor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
            executor.setThreadNamePrefix("thread-pool-");
            // rejection-policy:当pool已经达到max size的时候,如何处理新任务
            // CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            //执行初始化
            executor.initialize();
            return executor;
        }
    
        /**
         * 执行周期性或定时任务
         *
         * @return scheduledExecutorService
         */
        @Bean(name = "scheduledExecutorService")
        protected ScheduledExecutorService scheduledExecutorService() {
            BasicThreadFactory build = new BasicThreadFactory.Builder()
                    .namingPattern("schedule-pool-%d")
                    .daemon(true)
                    .build();
            return new ScheduledThreadPoolExecutor(CORE_POOL_SIZE, build) {
                @Override
                protected void afterExecute(Runnable r, Throwable t) {
                    super.afterExecute(r, t);
                    ThreadUtils.printException(r, t);
                }
            };
        }
    }
    
  4. 线程池的使用:

    • 注入执行器使用:

      @Autowired
      private AsyncTaskExecutor asyncExecutor;
      
      public CompletableFuture<AjaxResult> demo1() throws Exception {
          // Runnable接口无需返回值
          asyncExecutor.execute(() -> {
              ThreadUtils.sleep(1000);
              System.out.println("Runnable接口");
          });
          
          // Callable接口返回值为Future类型
          Future<AjaxResult> submit = asyncExecutor.submit(() -> {
              ThreadUtils.sleep(1000);
              System.out.println("Callable接口");
              return AjaxResult.success("Callable接口");
          });
          
          return submit;
      }
      
    • CompletableFuture 调用:

      @Autowired
      private AsyncTaskExecutor asyncExecutor;
      
      /**
       * 使用注入的线程池对象,执行异步方法
       */
      public CompletableFuture<AjaxResult> demo2() {
          // supplyAsync首先执行此线程
          return CompletableFuture.supplyAsync(studentMapper::selectAll, asyncExecutor)
              	// supplyAsync执行完成后,紧接着执行thenApply线程方法
                  .thenApply(res -> {
                      ThreadUtils.sleep(1000);
                      System.out.println("CompletableFuture对象实现异步");
                      return AjaxResult.success(res.stream()
                              .map(Student::getGuid)
                              .collect(Collectors.toList())
                      );
                  });
      }
      
    • spring异步注解 @Async

      /**
       * 指定线程池对象去执行
       */
      @Async("asyncExecutor")
      public CompletableFuture<AjaxResult> demo3() {
          ThreadUtils.sleep(1000);
          System.out.println("Async注解实现异步");
          AjaxResult result = AjaxResult.success("Async注解实现异步");
          return CompletableFuture.completedFuture(result);
      }
      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风於尘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值