欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

springboot实现异步任务

时间:2022-06-10 08:27:05|栏目:JAVA代码|点击:

本文实例为大家分享了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方法控制台来输出“数据正在传送”。

上一篇:Java日常练习题,每天进步一点点(20)

栏    目:JAVA代码

下一篇:Springboot跨域CORS处理实现原理

本文标题:springboot实现异步任务

本文地址:http://www.codeinn.net/misctech/204337.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有