springboot学习(五十五) springboot异步任务回调_文若书生的专栏-CSDN博客

spring的异步任务应该很多人都用过,但异步任务的回调用的比较少,其实可以使用异步任务回调来代替需要获取线程返回值的场景。

1、定义一个线程池

package com.iscas.biz.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 *
 * @author zhuquanwen
 * @vesion 1.0
 * @date 2021/2/26 10:41
 * @since jdk1.8
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {

    @Bean("wsExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
        executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 2);
        executor.setQueueCapacity(20000);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("wsExecutor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }

}

2、编写测试
注意函数的返回值一个Future,这里返回的AsyncResult是Futrue的一个实现类。

package com.iscas.biz.test.async;

import com.iscas.templet.common.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 测试异步回调
 *
 * @author zhuquanwen
 * @vesion 1.0
 * @date 2021/8/30 20:57
 * @since jdk1.8
 */
@RestController
@RequestMapping("/async/test")
public class AsyncControllerTest {

    @Async("wsExecutor")
    public Future<String> testAsync1() {
        // do something ...
        return new AsyncResult<>("lalalala");
    }

    @Async("wsExecutor")
    public Future<String> testAsync2() {
        // do something ...
        return new AsyncResult<>("yayayaya");
    }

    @GetMapping
    public ResponseEntity test() throws ExecutionException, InterruptedException {
        Future<String> stringFuture1 = testAsync1();
        Future<String> stringFuture2 = testAsync2();
        System.out.println(stringFuture1.get());
        System.out.println(stringFuture2.get());
        return new com.iscas.templet.common.ResponseEntity<>();
    }
}

别忘了在主类或配置类上添加一个@EnableAsync注解以开启异步任务
这样就大功告成了!!!


原网址: 访问
创建于: 2021-09-10 16:53:54
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论