异步任务_Spring Boot如何实现异步任务

本文介绍了 Spring Boot 实现异步任务的方法。因耗时任务同步执行会影响其他程序,所以需异步执行。具体步骤为:在启动类加 @EnableAsync 注解开启异步调用;创建异步执行类,加 @Component 和 @Async 注解;创建调用类;最后进行测试,验证方法异步执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

a27067f26378ea3e897a6bc915f5b3bd.png

点击上方 " JudyGirl "关注, 星标或置顶一起成长

前言

Spring Boot 中的另外一个任务:异步任务。所谓异步任务,其实就是异步执行程序,有些时候遇到一些耗时的的任务,如果一直卡等待,肯定会影响其他程序的执行,所以就让这些程序需要以异步的方式去执行。那么下面就来介绍 Spring Boot 如何实现异步任务。

一、使用注解@EnableAsync 开启异步调用方法

在 application 启动类中,加上@EnableAsync 注解,Spring Boot 会自动扫描异步任务。

package com.weiz;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
//扫描 mybatis mapper 包路径
@MapperScan(basePackages = "com.weiz.mapper")
//扫描 所有需要的包, 包含一些自用的工具类包 所在的路径
@ComponentScan(basePackages = {"com.weiz","org.n3r.idworker"})
//开启定时任务
@EnableScheduling
//开启异步调用方法
@EnableAsync
public class SpringBootStarterApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootStarterApplication.class, args);
}

}

二、创建异步执行类,定义@Component 及@Async 组件

创建 com.weiz.tasks 包,在 tasks 包里增加 AsyncTask 异步任务类,加上@Component 注解,然后在需要异步执行的方法前面加上@Async 注解,这样 Spring Boot 容器扫描到相关异步方法之后,调用时就会将这些方法异步执行。

package com.weiz.tasks;

import java.util.concurrent.Future;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

@Component
public class AsyncTask {

@Async
public Future doTask11() throws Exception {
long start = System.currentTimeMillis();
Thread.sleep(1000);
long end = System.currentTimeMillis();
System.out.println("任务 1 耗时:" + (end - start) + "毫秒");return new AsyncResult<>(true);
}
@Async
public Future doTask22() throws Exception {
long start = System.currentTimeMillis();
Thread.sleep(700);
long end = System.currentTimeMillis();
System.out.println("任务 2 耗时:" + (end - start) + "毫秒");return new AsyncResult<>(true);
}
@Async
public Future doTask33() throws Exception {
long start = System.currentTimeMillis();
Thread.sleep(600);
long end = System.currentTimeMillis();
System.out.println("任务 3 耗时:" + (end - start) + "毫秒");return new AsyncResult<>(true);
}
}

说明:@Async 加上这个注解,就表示该方法是异步执行方法。

三、调用

创建一个 DoTask 调用类,我们看看这几个方法,是怎么执行的:


package com.weiz.tasks;

import java.util.concurrent.Future;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("tasks")
public class DoTask {

    @Autowired
    private AsyncTask asyncTask;

    @RequestMapping("test1")
    public String test1() throws Exception {

        long start = System.currentTimeMillis();

        Future a = asyncTask.doTask11();
        Future b = asyncTask.doTask22();
        Future c = asyncTask.doTask33();while (!a.isDone() || !b.isDone() || !c.isDone()) {if (a.isDone() && b.isDone() && c.isDone()) {break;
            }
        }
        long end = System.currentTimeMillis();
        String times = "任务全部完成,总耗时:" + (end - start) + "毫秒";
        System.out.println(times);return times;
    }
}

四 测试

启动程序之后,在浏览器输入:http://localhost:8080/tasks/test1 。

从这个总耗时可以看出,三个方法确实是异步执行的。耗时接近时间最长的 doTask11 方法。

c4cbf892de26e0080b5fa49549fe918b.png
image

总结

以上,就把 Spring Boot 创建异步任务的方法简单介绍完了,是不是特别简单。

参考链接

Spring Boot 入门系列(九)如何实现异步执行任务

热门内容:
  • 记一次内存飙升的Windbg

  • 分布式架构数据存储设计与实践
  • 服务容错场景分析实现方案

a8290e0006fda95a4de67c2c312063d2.png           

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值