import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; @Configuration public class ExecutorConfig { @Bean public Executor asyncServiceExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5);// 配置核心线程数 executor.setMaxPoolSize(10);// 配置最大线程数 executor.setQueueCapacity(100);// 配置队列大小 executor.setThreadNamePrefix("async-service-");// 配置线程池中的线程的名称前缀 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());// 设置拒绝策略 executor.initialize();// 执行初始化 return executor; } }
*ThreadPoolExecutor的拒绝策略: 当线程池已经达到maxPoolSize的时候, 如何处理新任务.
*AsyncService
import java.util.concurrent.Future; public interface AsyncService { Future<String> getResult(); void doSomething(); }
*AsyncServiceImpl
import com.lky.service.AsyncService; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Component; import java.util.concurrent.Future; @Component @Async public class AsyncServiceImpl implements AsyncService { @Override public Future<String> getResult() { // 业务处理代码... return new AsyncResult<>("result"); } @Override public void doSomething() { // 业务处理代码... System.out.println("do something"); } }
import com.lky.service.AsyncService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; @Controller @EnableAsync public class AsyncController { @Autowired private AsyncService asyncService; @RequestMapping("/async") @ResponseBody public Map<String, String> async(@RequestBody Map<String, String> params) throws ExecutionException, InterruptedException { Future<String> asyncResult = asyncService.getResult(); System.out.println("asyncResult = " + asyncResult.get()); return null; } }