前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot异步任务

SpringBoot异步任务

作者头像
别团等shy哥发育
发布2023-02-25 16:11:09
3200
发布2023-02-25 16:11:09
举报
文章被收录于专栏:全栈开发那些事

SpringBoot异步任务

一、序言

在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的;但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,其实,在Spring 3.x之后,就已经内置了@Async来完美解决这个问题。

二、测试步骤

1、创建AsyncService

这里先不加@Async注解,并让线程休眠3秒

代码语言:javascript
复制
package com.atguigu.springboot.service;

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

@Service
public class AsyncService {
    //告诉spring,这是一个异步方法
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("处理数据中...");
    }
}

2、创建AsyncController

代码语言:javascript
复制
package com.atguigu.springboot.controller;

import com.atguigu.springboot.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AsyncController {
    @Autowired
    AsyncService asyncService;

    @GetMapping("/hello")
    public String hello(){
        asyncService.hello();
        return "success";
    }
}

3、不使用异步注解时运行测试:

结果:访问http://localhost:8080/hello时,回卡一会才能出现success

4、使用异步注解

在AsyncService的方法里加上@Async注解 在启动类上面加上@EnableAsync注解开启注解功能

5、测试

使用了异步注解之后,页面直接显示success,控制台隔了3秒也正常输出处理数据中,说明确实是异步执行的

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-06-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • SpringBoot异步任务
  • 一、序言
  • 二、测试步骤
    • 1、创建AsyncService
      • 2、创建AsyncController
        • 3、不使用异步注解时运行测试:
          • 4、使用异步注解
            • 5、测试
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档