Springboot任务管理(邮件发送异步同步,定时)

本文介绍了Springboot中任务管理的使用,包括异步任务(无返回值和有返回值)的实现,定时任务的配置与测试,以及发送纯文本邮件、带附件和图片邮件以及模板邮件的详细步骤。通过实例展示了如何提高系统效率和用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


前言

这章节来学习Springboot的异步处理


提示:以下是本篇文章正文内容,下面案例可供参考

一、任务管理的介绍

开发Web应用时,多数应用都具备任务调度功能。常见的任务包括异步任务、定时任务和发邮件任务。
我们以数据库报表为例看看任务调度如何帮助改善系统设计。报表可能是错综复杂的,用户可能需要很长时间找到需要的报表数据,此时,我们可以在这个报表应用中添加异步任务减少用户等待时间,从而提高用户体验;除此之外,还可以在报表应用中添加定时任务和邮件任务,以便用户可以安排在任何他们需要的时间定时生成报表,并在Email中发送。

二、使用步骤

需要用到的依赖启动器

<!--        添加Thymeleaf模板引擎依赖启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!--        添加邮件服务的依赖启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

1.异步任务

无返回值异步任务调用

1.Spring Boot 项目创建引入Web依赖
2.编写异步调用方法

代码如下(示例):

创建业务异步处理类

@Service
public class MyAsyncService {
    @Async
    public void sendSMS() throws Exception {
        System.out.println("调用短信验证码业务方法...");
        Long startTime = System.currentTimeMillis();
        Thread.sleep(5000);
        Long endTime = System.currentTimeMillis();
        System.out.println("短信业务执行完成耗时:" + (endTime - startTime));
    }}
3.开启基于注解的异步任务支持
在启动类中加入核心注解@EnableAsync
4.编写控制层业务调用方法
@RestController
public class MyAsyncController {
    @Autowired
    private MyAsyncService myService;
    @GetMapping("/sendSMS")
    public String sendSMS() throws Exception {
        Long startTime = System.currentTimeMillis();
        myService.sendSMS();
        Long endTime = System.currentTimeMillis();
        System.out.println("主流程耗时: "+(endTime-startTime));
        return "success";}

}
5.异步任务效果测试

在这里插入图片描述

上述异步方法是没有返回值的,这样主流程在执行异步方法时不会阻塞,而是继续向下执行主流程程序,直接向页面响应结果,而调用的异步方法会作为一个子线程单独执行,直到异步方法执行完成。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值