介绍
一些接口操作可以毕竟费时,而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)); } }
----------------------------------------------------
还有就是在一个springbean中使用多线程进行传入的数据处理可以这样做。
@Component @Slf4j public class DealThreadTask { private ExecutorService fixedThreadPool; //初始化线程池 @PostConstruct public void init() { ExecutorService fixedThreadPool = Executors.newFixedThreadPool(6); this.fixedThreadPool = fixedThreadPool; } public void execute(String name) { for (int j = 1; j < 3; j++) { List<TestLcc> testLccList = new ArrayList<>(); for (int i = 1; i < 3; i++) { testLccList.add(new TestLcc(i, name + i, (int) (Math.random() * 100))); } MoniotrTask moniotrTask = new MoniotrTask(testLccList, name + "线程" + j); if (!fixedThreadPool.isShutdown()) { fixedThreadPool.execute(moniotrTask); } } } public class MoniotrTask implements Runnable { private List<TestLcc> lccList; private String name; private Connection connection; public MoniotrTask(List<TestLcc> lccList, String name) { this.lccList = lccList; this.name = name; } @Override public void run() { System.out.println("启动" + name + "线程"); for (int i = 0; i < lccList.size(); i++) { System.out.println(lccList.get(i).toString()); } } } }