您的位置:首页 > 编程语言 > Java开发

Spring Boot 线程池实现的关键代码

2018-02-05 11:01 447 查看
启动类申明@EnableAsync

实现AsyncConfigurer

方法上申明 @Async

使用方法

启动类申明@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", "...", "...");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: