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));
      }
    }
  • 相关阅读:
    华为平板暴力禁用wifi
    传输层与数据层架构一二谈
    内外网访问控制设计
    机房通信网设计
    list add元素覆盖之前元素问题思考
    IIS8无法调用Oracle.DataAccess .dll问题
    线程令牌
    Socket解决粘包问题2
    Socket解决粘包问题1
    Socket异步通信学习三
  • 原文地址:https://www.cnblogs.com/woshuyuqiang/p/9394227.html
Copyright © 2011-2022 走看看