项目结构
D:JAVA-RES
├─.idea
│ └─libraries
├─.mvn
│ └─wrapper
├─src
│ ├─main
│ │ ├─java
│ │ │ └─yeye
│ │ │ └─devops
│ │ │ ├─annotation
│ │ │ ├─config
│ │ │ ├─control
│ │ │ ├─model
│ │ │ └─service
│ │ └─resources
│ │ ├─static
│ │ └─templates
│ └─test
│ └─java
│ └─yeye
│ └─devops
└─target
├─classes
│ └─yeye
│ └─devops
│ ├─annotation
│ ├─config
│ ├─control
│ ├─model
│ └─service
├─generated-sources
│ └─annotations
├─generated-test-sources
│ └─test-annotations
└─test-classes
└─yeye
└─devops
PS D:>
定义线程池
package yeye.devops.config;
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;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor(){
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
// 线程池维护线程的最少数量
taskExecutor.setCorePoolSize(5);
// 线程池中维护线程的最大数量
taskExecutor.setMaxPoolSize(10);
// 线程池维护线程所使用的缓冲队列
taskExecutor.setQueueCapacity(25);
//执行初始化
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
异步执行
package yeye.devops.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncTaskService {
@Async
public void executeAsyncTask() {
System.out.println("执行异步任务1--");
}
@Async
public void executeAsyncTaskPlus() {
System.out.println("执行异步任务2--" );
}
}
作用控制器
package yeye.devops.control;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import yeye.devops.service.AsyncTaskService;
@RestController
public class IndexController {
private static final Logger logger = LoggerFactory.getLogger(IndexController.class);
@Autowired
private AsyncTaskService asynctaskservice;
@GetMapping("api")
public String hello(){
logger.info("start----");
//调用service层的任务
asynctaskservice.executeAsyncTask();
logger.info("end----");
return "ok";
}
}