SpringBoot--任务:异步任务

01: 异步任务
02: 定时任务
03: 邮件任务

1. SpringBoot--异步任务

1.1 什么是同步和异步

  • 同步是阻塞模式,异步是非阻塞模式。
  • 同步就是指一个进程在执行某个请求的时候,若该请求需要一段时间才能返回信息,那么这个进程将会—直等待下去,知道收到返回信息才继续执行下去;
  • 异步是指进程不需要一直等下去,而是继续执行下面的操作,不管其他进程的状态。当有消息返回式系统会通知进程进行处理,这样可以提高执行的效率。

1.2 Java模拟一个异步请求(线程休眠)

在这里插入图片描述

AsyncService.java

package com.tian.asyncdemo.service;

import org.springframework.stereotype.Service;

@Service
public class AsyncService {
    public void hello() {
        try {
            System.out.println("数据正在处理");
            Thread.sleep(3000);
            System.out.println("数据处理完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

在这里插入图片描述

AsyncController.java

package com.tian.asyncdemo.controller;

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

/**
 * ClassName: AsyncController
 * Description:
 *
 * @author Administrator
 * @date 2021/6/6 19:48
 */
@RestController
public class AsyncController {
    @Autowired
    AsyncService asyncService;

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

运行结果:
在这里插入图片描述


1.3 使用异步

在Service的方法中使用@Async说这是一个异步方法,并在主入口上使用@EnableAsync开启异步支持
在这里插入图片描述

AsyncService.java

@Service
public class AsyncService {
    @Async
    public void hello() {
        try {
            System.out.println("数据正在处理");
            Thread.sleep(3000);
            System.out.println("数据处理完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

主入口上使用@EnableAsync开启异步支持
在这里插入图片描述


再次测试:
在这里插入图片描述



  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CodeJiao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值