springboot异步任务的实现

1.什么异步任务
同步:一定要等任务执行完了,得到结果,才执行下一个任务。
异步:不等任务执行完,直接执行下一个任务。
2.异步任务使用场景

在许多网站中,都会有发送邮件验证邮箱功能,执行该任务时,需要较长的时间,此时为了更好的用户体验,前端可以先返回完成的信息,后台去执行任务。

3.异步任务的实现步骤

首先模拟一个网站跳转的过程,假设某一个线程执行任务时需要5秒,结束以后才会进行下一步操作,我们令线程休眠五秒,然后通过controller进行页面跳转

service

package com.kuang.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {

    @Async
    public void hello(){
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在传送!");
    }
}

controller

package com.kuang.controller;

import com.kuang.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;

    @RequestMapping("/hello")
    public String hello(){
        asyncService.hello();
        return "OK";
    }

}

总结:

SpringBoot则可以使用更简便的方式来实现异步任务调度。我们只需要在Service层需要多线程处理的方法上加上@Async注解。
在这里插入图片描述

然后在主启动类上加上**@EnableAsync**注解来开启异步注解功能即可执行异步任务调度,此时执行可立即跳转然后再执行hello方法控制台来输出“数据正在传送”。
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在 Spring Boot 中,异步任务可以使用 `@Async` 注解来实现。使用 `@Async` 注解的方法会在一个单独的线程中执行,从而避免了长时间的阻塞。 以下是实现异步任务的步骤: 1. 在 Spring Boot 应用的主类上添加 `@EnableAsync` 注解,启用异步任务。 ```java @EnableAsync @SpringBootApplication public class Application { // ... } ``` 2. 在需要异步执行的方法上添加 `@Async` 注解。该方法的返回值类型必须是 `java.util.concurrent.Future`,以便在需要时获取异步任务的执行结果。 ```java @Service public class MyService { @Async public Future<String> doSomething() throws InterruptedException { // 模拟一个耗时的操作 Thread.sleep(5000); return new AsyncResult<>("Done"); } } ``` 3. 在需要调用异步方法的地方,使用 `Future` 对象获取异步任务的执行结果。 ```java @RestController public class MyController { @Autowired private MyService myService; @GetMapping("/async") public String asyncMethod() throws InterruptedException, ExecutionException { Future<String> future = myService.doSomething(); while (!future.isDone()) { // 等待异步任务完成 Thread.sleep(1000); } return future.get(); } } ``` 以上就是使用 `@Async` 注解实现异步任务的步骤。需要注意的是,异步任务的执行需要在一个单独的线程中进行,因此需要在应用程序中配置线程池,以便管理异步任务的线程。可以使用 Spring Boot 中的 `ThreadPoolTaskExecutor` 来实现线程池的配置。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值