@ASYNC,@ENABLEASYNC,ASYNCCONFIGURER 自定义线程

1. @ASYNC

在spring中,可以通过@EnableAsync + @Async两个注解非常快捷的实现异步。步骤如下:

启动类加上: @EnableAsync注解 并且在service上加上@Async注解

 
  1. @SpringBootApplication(

  2. exclude = {CodecsAutoConfiguration.class},

  3. scanBasePackages = {

  4. "com.arvato.config",

  5. "com.arvato.service",

  6. "com.arvato.controller"

  7. })

  8. @EnableAsync

  9. @MapperScan(basePackages = "com.arvato.mapper.config")

  10. public class WebFluxApplication {

  11. public static void main(String[] args) {

  12. SpringApplication.run(WebFluxApplication.class, args);

  13. }

  14. }

  15. @RestController

  16. @RequestMapping("/wxwork/sync")

  17. public class WxworkSyncController {

  18. @Autowired

  19. private WxworkSyncService wxworkSyncService;

  20. @GetMapping

  21. public Mono<String> sync() {

  22. // 异步处理业务

  23. wxworkSyncService.sync();

  24. return Mono.just("直接返回处理成功");

  25. }

  26. }

  27. @Service

  28. public class WxworkSyncService {

  29. @Async

  30. public void sync() {

  31. try {

  32. Thread.sleep(1000);

  33. } catch (InterruptedException e) {

  34. e.printStackTrace();

  35. }

  36. System.out.println(System.currentTimeMillis() + "--" + Thread.currentThread().getName());

  37. }

  38. }

然后疯狂发请求测试异步情况,并且打印线程名。我们发现默认情况下,每一次调用都是开启一个新的线程,截图如下:

可以看出来,@Async用的是SimpleAsyncTaskExecutor线程池,但是如果没有对SimpleAsyncTaskExecutor做策略配置的话,是不复用线程的,这是对服务器资源的浪费。 

2.自定义线程池

自定义线程池很简单,只要实现AsyncConfigurer接口,并且重写getAsyncExecutor方法。

 
  1. import lombok.extern.slf4j.Slf4j;

  2. import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;

  3. import org.springframework.context.annotation.Configuration;

  4. import org.springframework.scheduling.annotation.AsyncConfigurer;

  5. import org.springframework.scheduling.annotation.EnableAsync;

  6. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

  7. import java.util.Arrays;

  8. import java.util.concurrent.Executor;

  9. import java.util.concurrent.RejectedExecutionException;

  10. @Configuration

  11. @EnableAsync(proxyTargetClass = true)

  12. @Slf4j

  13. public class AsyncConfig implements AsyncConfigurer {

  14. @Override

  15. public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {

  16. return (ex, method, params) ->

  17. log.error("Unexpected error occurred invoking async method: " + method +

  18. ", args: " + Arrays.toString(params), ex);

  19. }

  20. /**

  21. * 自定义异步线程池

  22. * @return executor

  23. */

  24. @Override

  25. public Executor getAsyncExecutor() {

  26. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

  27. executor.setCorePoolSize(10);

  28. executor.setMaxPoolSize(20);

  29. executor.setQueueCapacity(1000);

  30. executor.setThreadNamePrefix("MyExecutor-");

  31. executor.setWaitForTasksToCompleteOnShutdown(false);

  32. // 设置拒绝策略

  33. executor.setRejectedExecutionHandler((r, e) -> {

  34. throw new RejectedExecutionException("Task " + r.toString() +

  35. " rejected from " +

  36. e.toString());

  37. });

  38. executor.initialize();

  39. return executor;

  40. }

  41. }

再次发请求测试:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值