zoukankan      html  css  js  c++  java
  • spring 异步任务 开启线程

    一些接口操作可以毕竟费时,而tomact线程的数量又是有限的,想要提高web吞吐量可以在spring里开启异步。spring默认的线程是有限的(反正默认的不太好之类的),需要自己手工配置个线程池效果会更好。

    @Configuration
    @EnableAsync//开启对异步任务的支持
    public class ThreadAsyncConfigurer  implements AsyncConfigurer {
      @Bean
      public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        //设置核心线程数
    threadPool.setCorePoolSize(10);
        //设置最大线程数
    threadPool.setMaxPoolSize(100);
        //线程池所使用的缓冲队列
    threadPool.setQueueCapacity(10);
        //等待任务在关机时完成--表明等待所有线程执行完
    threadPool.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时间 (默认为0,此时立即停止),并没等待xx秒后强制停止
    threadPool.setAwaitTerminationSeconds(60);
        //  线程名称前缀
    threadPool.setThreadNamePrefix("MyAsync-");
        // 初始化线程
    threadPool.initialize();
        return threadPool;
      }
    
      @Override
      public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
      }
    
    }
    
    

    使用就很方便 在接口上加上@Async,如果加在类上则表示该类的所有接口都是异步的

    @Service
    public class AsyncTaskService {
      @Async
      public void executeAsyncTask(Integer n){
        System.out.println("异步任务执行:"+n);
      }
    
    
      @Async
      public void executeAsyncTaskPlus(Integer n){
        System.out.println("异步任务执行+1:"+(n+1));
      }
    }
  • 相关阅读:
    .net core EF 入门笔记Code First
    Windows环境下安装MongodDB
    Ueditor1.4.3.3 富文本编辑器在图片不显示问题
    .net IIS网站部署Host文件简单应用
    .Net初学Less的安装与部署
    EF+MVC动态Lamda表达式拼接(学习笔记二)
    EF+MVC动态Lamda表达式拼接(学习笔记)
    区块链从入门到放弃
    Unity3D的update和FixedUpdate
    忽雷太极拳十三式
  • 原文地址:https://www.cnblogs.com/woshuyuqiang/p/9394227.html
Copyright © 2011-2022 走看看