• SpringBoot 异步接口


    1. @Api(tags = "测试异步")
    2. @RestController
    3. @RequestMapping("/api/async/v1")
    4. public class AsyncController {
    5. @Autowired
    6. private AsynService asynService;
    7. @ApiOperation("异步接口测试")
    8. @GetMapping("/test")
    9. public Object findDetailById() throws InterruptedException, ExecutionException {
    10. long currentTimeMillis = System.currentTimeMillis();
    11. asynService.asyncTest();
    12. long currentTimeMillis1 = System.currentTimeMillis();
    13. String result = "task任务总耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms";
    14. return result;
    15. }
    16. }
    1. public interface AsynService {
    2. void asyncTest();
    3. void asyncTest1() throws ExecutionException, InterruptedException;
    4. void asyncTest3();
    5. }
    1. @Service
    2. public class AsynServiceImpl implements AsynService {
    3. @Autowired
    4. private AsyncTask asyncTask;
    5. @Autowired
    6. AddressMapper addressMapper;
    7. @Autowired
    8. UserMapper userMapper;
    9. @Override
    10. @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    11. public void asyncTest() {
    12. Future task1 = null;
    13. try {
    14. task1 = asyncTask.t1();
    15. } catch (InterruptedException e) {
    16. e.printStackTrace();
    17. }
    18. Future task2 = null;
    19. try {
    20. task2 = asyncTask.t2();
    21. } catch (InterruptedException e) {
    22. e.printStackTrace();
    23. }
    24. Future task3 = null;
    25. try {
    26. task3 = asyncTask.t3();
    27. } catch (InterruptedException e) {
    28. e.printStackTrace();
    29. }
    30. for (;;) {
    31. if(task1.isDone() && task2.isDone() && task3.isDone()) {
    32. // 三个任务都调用完成,退出循环等待
    33. break;
    34. }
    35. }
    36. System.out.println("最后执行了");
    37. }
    38. @Override
    39. @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    40. public void asyncTest1() throws ExecutionException, InterruptedException {
    41. CompletableFuture future1=CompletableFuture.supplyAsync(new Supplier() {
    42. @Override
    43. public Long get() {
    44. UserDO userDO = new UserDO();
    45. userDO.setName("利益");
    46. userDO.setPwd("123");
    47. userDO.setMail("37396916374@qq.com");
    48. userMapper.insert(userDO);
    49. try {
    50. Thread.sleep(10000L);
    51. } catch (InterruptedException e) {
    52. e.printStackTrace();
    53. }
    54. return userDO.getId();
    55. }
    56. });
    57. CompletableFuture nestedResult = future1.thenCompose(value->
    58. CompletableFuture.supplyAsync(()->{
    59. AddressDO addressDO = new AddressDO();
    60. addressDO.setUserId(value);
    61. addressDO.setCity("南京");
    62. addressDO.setPhone("18710555348");
    63. addressMapper.insert(addressDO);
    64. try {
    65. Thread.sleep(5000L);
    66. } catch (InterruptedException e) {
    67. e.printStackTrace();
    68. }
    69. return addressDO.getId();
    70. }));
    71. while (true){
    72. if(future1.isDone()&& nestedResult.isDone()){
    73. break;
    74. }
    75. }
    76. System.out.println(nestedResult.get());
    77. }
    78. @Override
    79. @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    80. public void asyncTest3() {
    81. CompletableFuture future1=CompletableFuture.supplyAsync(new Supplier() {
    82. @Override
    83. public Long get() {
    84. UserDO userDO = new UserDO();
    85. userDO.setName("利益");
    86. userDO.setPwd("123");
    87. userDO.setMail("33296912374@qq.com");
    88. userMapper.insert(userDO);
    89. return userDO.getId();
    90. }
    91. });
    92. CompletableFuture nestedResult = future1.thenCompose(value->
    93. CompletableFuture.supplyAsync(()->{
    94. AddressDO addressDO = new AddressDO();
    95. addressDO.setUserId(value);
    96. addressDO.setCity("南京");
    97. addressDO.setPhone("18710555348");
    98. addressMapper.insert(addressDO);
    99. return addressDO.getId();
    100. }));
    101. while (true){
    102. if(future1.isDone()&& nestedResult.isDone()){
    103. break;
    104. }
    105. }
    106. int i = 10/0;
    107. }
    108. }
    1. @Service
    2. public class AsyncTask {
    3. @Autowired
    4. UserMapper userMapper;
    5. @Autowired
    6. AddressMapper addressMapper;
    7. public Future t1() throws InterruptedException {
    8. return task1();
    9. }
    10. public Future t2() throws InterruptedException {
    11. return task2();
    12. }
    13. public Future t3() throws InterruptedException {
    14. return task3();
    15. }
    16. @Async("asyncServiceExecutor")
    17. public Future task1() throws InterruptedException{
    18. long currentTimeMillis = System.currentTimeMillis();
    19. AddressDO addressDO = new AddressDO();
    20. addressDO.setCity("南京");
    21. addressDO.setPhone("18710555348");
    22. addressMapper.insert(addressDO);
    23. long currentTimeMillis1 = System.currentTimeMillis();
    24. System.out.println("task1任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
    25. return new AsyncResult(addressDO);
    26. }
    27. @Async("asyncServiceExecutor")
    28. public Future task2() throws InterruptedException{
    29. long currentTimeMillis = System.currentTimeMillis();
    30. UserDO userDO = new UserDO();
    31. userDO.setName("利益");
    32. userDO.setPwd("123");
    33. userDO.setMail("3499283774@qq.com");
    34. userMapper.insert(userDO);
    35. test7();
    36. long currentTimeMillis1 = System.currentTimeMillis();
    37. System.out.println("task2任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
    38. return new AsyncResult(userDO);
    39. }
    40. public void test7() throws InterruptedException {
    41. FixedThreadPoolUtil.doExecutor(() -> {
    42. try {
    43. task4();
    44. } catch (InterruptedException e) {
    45. e.printStackTrace();
    46. }
    47. });
    48. FixedThreadPoolUtil.doExecutor(() -> {
    49. try {
    50. task5();
    51. } catch (InterruptedException e) {
    52. e.printStackTrace();
    53. }
    54. });
    55. }
    56. public void task4() throws InterruptedException {
    57. long currentTimeMillis = System.currentTimeMillis();
    58. AddressDO addressDO = new AddressDO();
    59. addressDO.setCity("ti京");
    60. addressDO.setPhone("18710555348");
    61. addressMapper.insert(addressDO);
    62. Thread.sleep(4000L);
    63. long currentTimeMillis1 = System.currentTimeMillis();
    64. System.out.println("task4任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
    65. }
    66. public void task5() throws InterruptedException {
    67. long currentTimeMillis = System.currentTimeMillis();
    68. AddressDO addressDO = new AddressDO();
    69. addressDO.setCity("东京");
    70. addressDO.setPhone("18710555348");
    71. addressMapper.insert(addressDO);
    72. Thread.sleep(6000L);
    73. long currentTimeMillis1 = System.currentTimeMillis();
    74. System.out.println("task5任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
    75. }
    76. @Async("asyncServiceExecutor")
    77. public Future task3() throws InterruptedException{
    78. long currentTimeMillis = System.currentTimeMillis();
    79. Thread.sleep(3000L);
    80. long currentTimeMillis1 = System.currentTimeMillis();
    81. System.out.println("task3任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
    82. return new AsyncResult("");
    83. }
    84. }
    1. @Configuration
    2. @Slf4j
    3. public class ThreadPoolConfiguration {
    4. @Bean(name = "defaultThreadPoolExecutor", destroyMethod = "shutdown")
    5. public ThreadPoolExecutor systemCheckPoolExecutorService(){
    6. return new ThreadPoolExecutor(3,10,60, TimeUnit.SECONDS,
    7. new LinkedBlockingDeque<>(10000),
    8. Executors.defaultThreadFactory(),
    9. (r,e)->System.out.println("is full"));
    10. }
    11. }
    1. /**
    2. * 多线程的配置
    3. *
    4. * @author llh
    5. * @version 1.0
    6. * @date 2021/11/16 17:49
    7. */
    8. @Configuration
    9. @EnableAsync
    10. @Slf4j
    11. public class ExecutorConfig {
    12. @Value("${async.executor.thread.core_pool_size}")
    13. private int corePoolSize;
    14. @Value("${async.executor.thread.max_pool_size}")
    15. private int maxPoolSize;
    16. @Value("${async.executor.thread.queue_capacity}")
    17. private int queueCapacity;
    18. @Value("${async.executor.thread.name.prefix}")
    19. private String namePrefix;
    20. @Bean(name = "asyncServiceExecutor")
    21. public Executor asyncServiceExecutor() {
    22. log.info("线程池启动了");
    23. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    24. //配置核心线程数
    25. executor.setCorePoolSize(corePoolSize);
    26. //配置最大线程数
    27. executor.setMaxPoolSize(maxPoolSize);
    28. //配置队列大小
    29. executor.setQueueCapacity(queueCapacity);
    30. //配置线程池中的线程的名称前缀
    31. executor.setThreadNamePrefix(namePrefix);
    32. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    33. //执行初始化
    34. executor.initialize();
    35. return executor;
    36. }
    37. }
    1. async.executor.thread.core_pool_size=4
    2. async.executor.thread.max_pool_size=8
    3. async.executor.thread.queue_capacity=135
    4. async.executor.thread.name.prefix= ticketManager-worker-

  • 相关阅读:
    图像处理学习笔记-09-形态学图像处理
    如何学会从产品经理角度去思考问题?
    JavaScript---函数arguments参数直接获取的方式
    【Spring Cloud】Nacos注册中心
    电梯安全监测丨S271W无线水浸传感器用于电梯机房/电梯基坑水浸监测
    vue15
    Spring5应用之事务处理
    【掌握K8S集群部署】手把手真正实现Kubernetes集群的配置与部署(附问题解决方法)
    SSL证书也会失效?什么情况下SSL证书会失效呢?
    成为数字游民,他们为何「All in Web3」?
  • 原文地址:https://blog.csdn.net/m0_37647376/article/details/126237991