springboot-异步、定时、邮件任务

本文介绍了如何在SpringBoot项目中实现异步任务处理,包括使用`@Async`注解简化多线程管理,定时任务的`@Scheduled`和Cron表达式,以及集成JavaMail发送邮件。详细讲解了如何配置和测试这些功能。
摘要由CSDN通过智能技术生成

一、异步任务

1、创建项目

2、创建一个service包

3、创建一个类AsyncService

异步处理还是非常常用的,比如我们在网站上发送邮件,后台会去发送邮件,此时前台会造成响应不动,直到邮件发送完毕,响应才会成功,所以我们一般会采用多线程的方式去处理这些任务。

编写方法,假装正在处理数据,使用线程设置一些延时,模拟同步等待的情况;

4、编写controller包

5、编写AsyncController类

package com.example.springboottask.controller;

import com.example.springboottask.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";
    }

}

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

问题:我们如果想让用户直接得到消息,就在后台使用多线程的方式进行处理即可,但是每次都需要自己手动去编写多线程的实现的话,太麻烦了,我们只需要用一个简单的办法,在我们的方法上加一个简单的注解即可,如下:

7、给hello方法添加@Async注解;

  1. @EnableAsync //开启异步注解功能

package com.example.springboottask.service;

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

@Service
public class AsyncService {
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("业务进行中....");
    }
}

 @Async注解用于声明一个方法是异步的,在Spring框架中使用。这个注解的主要作用是将方法的执行委托给Spring的任务执行器(TaskExecutor),以便在单独的线程中运行,从而实现异步处理。使用@Async注解可以提升应用程序的性能,特别是在处理耗时较长的操作时,因为它允许调用者不必等待方法执行完毕就可以继续执行其他操作。

SpringBoot就会自己开一个线程池,进行调用!但是要让这个注解生效,我们还需要在主程序上添加一个注解@EnableAsync ,开启异步注解功能;

 二、定时任务

项目开发中经常需要执行一些定时任务,比如需要在每天凌晨的时候,分析一次前一天的日志信息,Spring为我们提供了异步执行任务调度的方式,提供了两个接口。

  • TaskExecutor接口

  • TaskScheduler接口

两个注解:

  • @EnableScheduling

  • @Scheduled

cron表达式:

测试步骤:

1、创建一个ScheduledService

我们里面存在一个hello方法,他需要定时执行,怎么处理呢?

package com.example.springmvcexamples.example07.timer;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
 
@Component
@Slf4j
public class MyTimer {
    @Scheduled(cron = "0 0 8 10 * ?")
    public void paySalary() {
        log.debug("Your salary has been paid!");
    }
}

2、这里写完定时任务之后,我们需要在主程序上增加@EnableScheduling 开启定时任务功能

package com.example.springmvcexamples.example07.timer;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
 
@Component
@Slf4j
public class MyTimer {
    @Scheduled(cron = "0 0 8 10 * ?")
    public void paySalary() {
        log.debug("Your salary has been paid!");
    }
}

三、邮件任务

邮件发送,在我们的日常开发中,也非常的多,Springboot也帮我们做了支持

  • 邮件发送需要引入spring-boot-start-mail

  • SpringBoot 自动配置MailSenderAutoConfiguration

  • 定义MailProperties内容,配置在application.yml中

  • 自动装配JavaMailSender

  • 测试邮件发送

测试:

1、引入pom依赖

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

2、配置文件:

spring.mail.username=33430657322@qq.com
spring.mail.password=你的qq授权码
spring.mail.host=smtp.qq.com
# qq需要配置ssl
spring.mail.properties.mail.smtp.ssl.enable=true

获取授权码:在QQ邮箱中的设置->账户->开启pop3和smtp服务

3、Spring单元测试

package com.example.springboottask;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import java.io.File;

@SpringBootTest
class SpringbootTaskApplicationTests {

    @Autowired
    JavaMailSenderImpl mailSender;

    @Test
    public void contextLoads() {
        //邮件设置1:一个简单的邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("通知-明天来这听课"); // 设置邮件主题
        message.setText("今晚7:30开会"); // 设置邮件正文

        message.setTo("24736743@qq.com"); // 设置收件人邮箱
        message.setFrom("24736743@qq.com"); // 设置发件人邮箱
        mailSender.send(message); // 发送邮件
    }

    @Test
    public void contextLoads2() throws MessagingException {
        //邮件设置2:一个复杂的邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage(); // 创建一个MimeMessage对象
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); // 创建一个MimeMessageHelper对象,用于构建复杂邮件

        helper.setSubject("通知-明天来这听课"); // 设置邮件主题
        helper.setText("<b style='color:red'>今天 7:30来开会</b>",true); // 设置邮件正文,支持HTML格式

        //发送附件
        helper.addAttachment("1.jpg",new File("")); // 添加附件1
        helper.addAttachment("2.jpg",new File("")); // 添加附件2

        helper.setTo("24736743@qq.com"); // 设置收件人邮箱
        helper.setFrom("24736743@qq.com"); // 设置发件人邮箱

        mailSender.send(mimeMessage); // 发送邮件
    }


}

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

烟雨平生9527

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

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

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

打赏作者

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

抵扣说明:

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

余额充值