SpringBoot实战(五)异步任务

文章目录

  • 1. 简介
  • 2. SpringBoot异步任务实现
    • 2.1 实现一个简单的异步任务
      • 2.1.1 添加@EnableAsync注解,开启异步任务功能
      • 2.1.2 定义异步任务
      • 2.1.3 定义接口
      • 2.1.4 结果
    • 2.2 使用自定义的线程池配置
      • 2.2.1 实现AsyncConfigurer接口
      • 2.2.2 在AsyncServiceImpl中添加代码
      • 2.2.3 结果

1. 简介

​ 异步指的是每一个任务有一个或多个回调函数(callback),前一个任务结束后,不是执行后一个任务,而是执行回调函数,后一个任务则是不等前一个任务结束就执行,所以程序的执行顺序与任务的排列顺序是不一致的、异步的。

2. SpringBoot异步任务实现

2.1 实现一个简单的异步任务

步骤如下:

2.1.1 添加@EnableAsync注解,开启异步任务功能

@EnableAsync
@SpringBootApplication
public class UtilsApplication {
    public static void main(String[] args) {
        SpringApplication.run(UtilsApplication.class, args);
    }
}

2.1.2 定义异步任务

public interface AsyncService {

    Future<String> doTask1()throws Exception;
    Future<String> doTask2()throws Exception;
    Future<String> doTask3()throws Exception;
}
@Service
public class AsyncServiceImpl implements AsyncService {

    public static Random random =new Random();

    @Async
    @Override
    public Future<String> doTask1() throws Exception {
        System.out.println("开始做任务一");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        System.out.println("完成任务一,耗时:" + (end - start) + "毫秒");
        return new AsyncResult<>("任务一完成");
    }

    @Async
    @Override
    public Future<String> doTask2()throws Exception {
        System.out.println("开始做任务二");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        System.out.println("完成任务二,耗时:" + (end - start) + "毫秒");
        return new AsyncResult<>("任务二完成");
    }

    @Async
    @Override
    public Future<String> doTask3() throws Exception{
        System.out.println("开始做任务三");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
        return new AsyncResult<>("任务三完成");
    }
}

2.1.3 定义接口

@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;

    @RequestMapping("/async")
    public String getEntityById() throws Exception {

        long start = System.currentTimeMillis();

        Future<String> task1 = asyncService.doTask1();
        Future<String> task2 = asyncService.doTask2();
        Future<String> task3 = asyncService.doTask3();

        while(true) {
            if(task1.isDone() && task2.isDone() && task3.isDone()) {
                // 三个任务都调用完成,退出循环等待
                break;
            }
            Thread.sleep(1000);
        }

        long end = System.currentTimeMillis();

        return "任务全部完成,总耗时:" + (end - start) + "毫秒";
    }
}

2.1.4 结果

SpringBoot实战(五)异步任务_第1张图片

{"code":200,"message":"成功","data":"任务全部完成,总耗时:10006毫秒"}

2.2 使用自定义的线程池配置

@EnableAsync中的注释:

 *By default, Spring will be searching for an associated thread pool definition:
 * either a unique {@link org.springframework.core.task.TaskExecutor} bean in the context,
 * or an {@link java.util.concurrent.Executor} bean named "taskExecutor" otherwise. If
 * neither of the two is resolvable, a {@link org.springframework.core.task.SimpleAsyncTaskExecutor}
 * will be used to process async method invocations. Besides, annotated methods having a
 * {@code void} return type cannot transmit any exception back to the caller. By default,
 * such uncaught exceptions are only logged.

2.2.1 实现AsyncConfigurer接口

@Slf4j
@Configuration
public class AsyncConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
         ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
         executor.setCorePoolSize(7);
         executor.setMaxPoolSize(42);
         executor.setQueueCapacity(11);
         executor.setThreadNamePrefix("MyExecutor-");
         executor.initialize();
         return executor;
     }

    /**
     * 异步任务中异常处理
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler() {
            @Override
            public void handleUncaughtException(Throwable ex, Method method, Object... params) {
                log.error("=========================="+ex.getMessage()+"=======================", ex);
                log.error("exception method:"+method.getName());
            }
        };
    }
}

2.2.2 在AsyncServiceImpl中添加代码

System.out.println("当前线程:"+Thread.currentThread().getName());

2.2.3 结果

当前线程:MyExecutor-3 执行任务3
当前线程:MyExecutor-1 执行任务1
当前线程:MyExecutor-2 执行任务2
完成任务二,耗时:6734毫秒
完成任务一,耗时:7514毫秒
完成任务三,耗时:9308毫秒
{"code":200,"message":"成功","data":"任务全部完成,总耗时:10011毫秒"}

你可能感兴趣的:(SpringBoot,spring,boot,java,spring)