springboot-整合任务

学习视频: https://www.bilibili.com/video/BV1PE411i7CV?p=51

1.1 异步任务

在网站上发送邮件,后台会去发送邮件,此时前台会造成响应不动,直到邮件发送完毕,响应才会成功,所以一般会采用多线程的方式去处理这些任务。
编写方法,假装正在处理数据,使用线程设置一些延时,模拟同步等待的情况。

1、项目目录

2、编写AsyncService

package cn.guardwhy.service;

import org.springframework.stereotype.Service;

@Service
public class AsyncService {
   
    public void hello(){
   

        try {
   
            // 休眠3秒
            Thread.sleep(30000);
        } catch (InterruptedException e) {
   
            e.printStackTrace();
        }
        // 输出结果
        System.out.println("数据处理中.....");
    }
}

3、编写AsyncController类

package cn.guardwhy.controller;

import cn.guardwhy.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(); // 停止3S,转圈
        return "success";
    }
}

4、启动项目,访问http://localhost:8080/hello进行测试,3秒后出现了success,这是同步等待的情况。

5、 给hello方法添加@Async注解,可以在用户直接得到消息,在后台使用多线程的方式进行处理。

package
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值