1.概述
Spring
是經過任務執行器(TaskExecutor
)來實現多線程和併發編程,使用ThreadPoolTaskExecutor
來建立一個基於線城池的TaskExecutor
。在使用線程池的大多數狀況下都是異步非阻塞的。咱們配置註解@EnableAsync
能夠開啓異步任務。而後在實際執行的方法上配置註解@Async
上聲明是異步任務。
2.代碼
package com.example.testproject.config;
import java.util.concurrent.Executor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/*
*1. 利用EnableAsync來開啓Springboot對於異步任務的支持
*2. 配置類實現接口AsyncConfigurator,返回一個ThreadPoolTaskExecutor線程池對象。
*/
@Configuration
@EnableAsync
public class ThreadConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(8);
executor.setMaxPoolSize(1000);
executor.setQueueCapacity(500);
executor.setKeepAliveSeconds(30000);
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
package com.example.testproject.service;
public interface AsyncTestService {
void test(int i);
}
package com.example.testproject.service.imp;
import com.example.testproject.service.AsyncTestService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncTestServiceImp implements AsyncTestService {
@Override
@Async //經過@Async註解代表該方法是異步方法,若是註解在類上,那代表這個類裏面的全部方法都是異步的。
public void test(int i) {
System.out.println("線程" + Thread.currentThread().getName() + " 執行異步任務:" + i);
}
}