版权声明:本文为博主hecb原创文章,未经博主允许不得转载。 https://blog.csdn.net/blvyoucan/article/details/79257640
启动类申明@EnableAsync
@SpringBootApplication
@EnableAsync
public classApplication {
public static void main(String[] args){
SpringApplication.run(Application.class);
}
}
实现AsyncConfigurer
@Configuration
@ComponentScan("...")
public class AsyncConfiguration implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor tp = new ThreadPoolTaskExecutor();
tp.setCorePoolSize(5);
tp.setMaxPoolSize(10);
//线程空闲超过这个时间,就回收该线程↓
tp.setKeepAliveSeconds(3000);
//队列长度↓
tp.setQueueCapacity(1000);
tp.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
tp.initialize();
return tp;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
//异常处理↓
return null;
}
}
方法上申明 @Async
@Component
public class AsyncTest {
@Async
public void testVoid(String s) {
//无返回值
}
@Async
public Future<String> testFuture(String S){
//有返回值
return new AsyncResult<String> (s);
}
}
使用方法
@Controller
@RequestMapping("/")
public class TestControllers {
//在需要的地方注入↓
@Autowired
private AsyncTest asyncTest;
@GetMapping
public ModelAndView index(){
asyncTest.testVoid("...");
asyncTest.testFuture("...");
return new ModelAndView("index", "...", "...");
}
}