springboot实现异步任务

作者:微滑低 时间:2023-04-23 01:25:21 

本文实例为大家分享了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注解。

springboot实现异步任务

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

springboot实现异步任务

来源:https://blog.csdn.net/weixin_49092628/article/details/117374536

标签:springboot,异步任务
0
投稿

猜你喜欢

  • C# 索引器的使用教程

    2022-08-25 05:11:59
  • 微信公众号服务号推送模板消息设置方法(后端java)

    2023-11-20 08:27:58
  • C#动态生成DropDownList执行失败原因分析

    2023-08-30 22:37:28
  • java获取文件的inode标识符的方法

    2021-06-19 15:10:49
  • Java 实战图书管理系统的实现流程

    2023-12-19 05:11:13
  • Spring Cloud项目前后端分离跨域的操作

    2022-05-20 08:11:16
  • java抓取网页或文件中的邮箱号码

    2023-07-30 19:19:28
  • Java发送http请求的示例(get与post方法请求)

    2021-09-29 23:21:40
  • 通过实例解析Socket套接字通信原理

    2023-11-02 20:17:35
  • MyBatis-Plus自动填充功能失效导致的原因及解决

    2023-05-11 13:16:08
  • android使用PullToRefresh框架实现ListView下拉刷新上拉加载更多

    2023-05-23 05:29:16
  • Android使用TextView跑马灯效果

    2022-05-20 20:07:20
  • c#如何使用 XML 文档功能

    2023-12-25 03:44:33
  • C#使用yield关键字构建迭代器详解

    2023-02-09 12:48:49
  • Java matches类,Pattern类及matcher类用法示例

    2022-02-21 22:39:52
  • 一篇文章带你复习java知识点

    2023-01-15 09:39:38
  • Java语言描述二叉树的深度和宽度

    2021-12-02 10:59:34
  • Java中的 stop the world是什么呢

    2022-09-11 21:32:42
  • C# LINQ to XML应用介绍

    2021-06-11 05:59:07
  • java原码补码反码关系解析

    2021-12-26 20:30:29
  • asp之家 软件编程 m.aspxhome.com