首页 > 其他分享 >SpringBoot的异步、定时、邮件任务

SpringBoot的异步、定时、邮件任务

时间:2022-09-01 21:35:14浏览次数:93  
标签:异步 15 SpringBoot helper 10 mail public 邮件

13、异步、定时、邮件任务

13.1、前言

在我们的工作中,常常会用到异步处理任务,比如我们在网站上发送邮件,后台会去发送邮件,此时前台会造成响应不动,直到邮件发送完毕,响应才会成功,所以我们一般会采用多线程的方式去处理这些任务。还有一些定时任务,比如需要在每天凌晨的时候,分析一次前一天的日志信息。还有就是邮件的发送,微信的前身也是邮件服务呢?这些东西都是怎么实现的呢?其实SpringBoot都给我们提供了对应的支持,我们上手使用十分的简单,只需要开启一些注解支持,配置一些配置文件即可!那我们来看看吧~

13.2、异步任务

1、创建一个service包

2、创建一个类AsyncService

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

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

@Service
public class AsyncService {

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

3、编写controller包

4、编写AsyncController类

我们去写一个Controller测试一下

@RestController
public class AsyncController {

   @Autowired
   AsyncService asyncService;

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

}

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

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

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

//告诉Spring这是一个异步方法
@Async
public void hello(){
   try {
       Thread.sleep(3000);
  } catch (InterruptedException e) {
       e.printStackTrace();
  }
   System.out.println("业务进行中....");
}

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

@EnableAsync //开启异步注解功能
@SpringBootApplication
public class SpringbootTaskApplication {

   public static void main(String[] args) {
       SpringApplication.run(SpringbootTaskApplication.class, args);
  }

}

7、重启测试,网页瞬间响应,后台代码依旧执行!

13.3、定时任务

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

  • TaskExecutor接口
  • TaskScheduler接口

两个注解:

  • @EnableScheduling
  • @Scheduled

cron表达式:

字段 允许值 允许的特殊符号
0-59 , - * /
0-59 , - * /
小时 0-23 , - * /
日期 1-31 , - * ?/ L W C
月份 1-12 , - * /
星期 0-7 , - * ?/ L W C
特殊符号 代表含义
, 枚举
- 区间
* 任意
/ 步长
? 日、星期冲突匹配
L 最后
W 工作日
C 和canlendar联系后计算过的值
# 星期,4#2,第2个星期三

测试步骤:

1、创建一个ScheduledService

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

@Service
public class ScheduledService {
   
   //秒   分   时     日   月   周几
   //0 * * * * MON-FRI
   //注意cron表达式的用法;
   @Scheduled(cron = "0 * * * * 0-7")
   public void hello(){
       System.out.println("hello.....");
  }
}

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

@EnableAsync //开启异步注解功能
@EnableScheduling //开启基于注解的定时任务
@SpringBootApplication
public class SpringbootTaskApplication {

   public static void main(String[] args) {
       SpringApplication.run(SpringbootTaskApplication.class, args);
  }

}

3、我们来详细了解下cron表达式;

http://www.bejson.com/othertools/cron/

4、常用的表达式

(1)0/2 * * * * ?   表示每2秒 执行任务
(1)0 0/2 * * * ?   表示每2分钟 执行任务
(1)0 0 2 1 * ?   表示在每月的1日的凌晨2点调整任务
(2)0 15 10 ? * MON-FRI   表示周一到周五每天上午10:15执行作业
(3)0 15 10 ? 6L 2002-2006   表示2002-2006年的每个月的最后一个星期五上午10:15执行作
(4)0 0 10,14,16 * * ?   每天上午10点,下午2点,4点
(5)0 0/30 9-17 * * ?   朝九晚五工作时间内每半小时
(6)0 0 12 ? * WED   表示每个星期三中午12点
(7)0 0 12 * * ?   每天中午12点触发
(8)0 15 10 ? * *   每天上午10:15触发
(9)0 15 10 * * ?     每天上午10:15触发
(10)0 15 10 * * ?   每天上午10:15触发
(11)0 15 10 * * ? 2005   2005年的每天上午10:15触发
(12)0 * 14 * * ?     在每天下午2点到下午2:59期间的每1分钟触发
(13)0 0/5 14 * * ?   在每天下午2点到下午2:55期间的每5分钟触发
(14)0 0/5 14,18 * * ?     在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
(15)0 0-5 14 * * ?   在每天下午2点到下午2:05期间的每1分钟触发
(16)0 10,44 14 ? 3 WED   每年三月的星期三的下午2:10和2:44触发
(17)0 15 10 ? * MON-FRI   周一至周五的上午10:15触发
(18)0 15 10 15 * ?   每月15日上午10:15触发
(19)0 15 10 L * ?   每月最后一日的上午10:15触发
(20)0 15 10 ? * 6L   每月的最后一个星期五上午10:15触发
(21)0 15 10 ? * 6L 2002-2005   2002年至2005年的每月的最后一个星期五上午10:15触发
(22)0 15 10 ? * 6#3   每月的第三个星期五上午10:15触发

13.4、邮件任务

邮件发送,在我们的日常开发中,也非常的多,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>

看它引入的依赖,可以看到 jakarta.mail

<dependency>
   <groupId>com.sun.mail</groupId>
   <artifactId>jakarta.mail</artifactId>
   <version>1.6.4</version>
   <scope>compile</scope>
</dependency>

2、查看自动配置类:MailSenderAutoConfiguration发现导入了MailSenderAutoConfiguration类,它有一个bean,JavaMailSenderImpl,

3、查看一下有哪些配置

@ConfigurationProperties(prefix = "spring.mail")
public class MailProperties {

	private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

	private String host;
	private Integer port;
	private String username;
	private String password;
	private String protocol = "smtp";
	private Charset defaultEncoding = DEFAULT_CHARSET;
	private Map<String, String> properties = new HashMap<>();
	private String jndiName;
}

4、配置文件:

[email protected]
spring.mail.password=你的qq邮箱授权码 #(需要去邮箱里面开启POP3/SMTP服务,会有一个授权码)
spring.mail.host=smtp.qq.com
# qq邮箱需要配置ssl,其他不用
spring.mail.properties.mail.smtp.ssl.enable=true

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

5、Spring单元测试

import org.junit.jupiter.api.Test;
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 javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@SpringBootTest
class Springboot10TaskApplicationTests {

    @Resource
    JavaMailSenderImpl mailSender;

    @Test
    void contextLoads() {
        // 邮件设置1:一个简单的邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("重庆邮电大学考研通知");
        message.setText("恭喜你成功上岸,请于2023年9月1日到校报道");

        message.setTo("[email protected]");
//        message.setTo("[email protected]");
        message.setFrom("[email protected]");

        mailSender.send(message);
    }

    @Test
    void contextLoads1() throws MessagingException {
        // 邮件设置2:一个复杂的邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        // 组装
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        // 正文
        helper.setSubject("重庆邮电大学考研通知2");
        helper.setText("<p style='color:red;'>恭喜你成功上岸,请于2023年9月1日到校报道</p>", true);

        // 附件
        helper.addAttachment("1.png",new File("C:\\Users\\Administrator\\Desktop\\1.png"));

        helper.setTo("[email protected]");
        helper.setFrom("[email protected]");

        mailSender.send(mimeMessage);
    }

    /*
     * 描述: 邮件发送工具类
     * @param subject:发送标题
     * @param text:发送内容
     * @param to:发送给
     * @param from: 从哪发送
     * @param flag: 是否启用html标签
     * @return: void
     */
    public void sendMail(String subject, String text, String to, String from, Boolean flag) throws MessagingException {
        // 一个复杂的邮件(工具类)
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        // 组装
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, flag);

        // 正文
        helper.setSubject(subject);
        helper.setText(text, flag);

        // 附件
        //helper.addAttachment("1.png",new File("C:\\Users\\Administrator\\Desktop\\1.png"));

        helper.setTo(to);
        helper.setFrom(from);

        mailSender.send(mimeMessage);
    }
}

查看邮箱,邮件接收成功!


END

标签:异步,15,SpringBoot,helper,10,mail,public,邮件
From: https://www.cnblogs.com/lyluoye/p/16647886.html

相关文章

  • SpringBoot简单使用(2)
    1.2.7:CommandLineRunner接口:开发中可能会有这样的情景。需要在容器启动后执行一些内容。比如读取配置文件,数据库连接之类的。SpringBoot给我们提供了两个接口来帮助我......
  • Springboot整合Sentinel实现流控
    在Springboot项目中整合Sentinel实现流控,Gateway整合Sentinel见Gateway整合Sentinel,Sentinel-daahboard的改造见Sentinel-dashboard改造(普通流控和网关流控规则持久化到Nac......
  • SpringBoot上传文件
    前端使用ElementUI+Vue后端使用SpringBoot1前端代码1.0组件导入&初始化导入ElementUI、Axios、Vue的资源。完成Vue的初始化和生效区域的设置。这些资源都能找到,把......
  • SpringBoot-Http请求工具类
    一、编写请求配置类importcom.alibaba.fastjson.JSONObject;importorg.springframework.context.annotation.Configuration;importorg.springframework.http.*;imp......
  • springboot整合redis,设置缓存过期时间
    注:redis服务器要先开启!或者连接远程服务器上的Redis,但是依然要开启服务,不然会一直TimeOut!Pom文件添加依赖<dependency><groupId>org.springframework.boot</......
  • SpringBoot项目引入Swagger接口文档
    一、在项目中引入Swagger依赖<!--swagger--><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifa......
  • springboot+Vue项目允许跨域
    packagecom.example.demo.itkb.user.config;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotat......
  • SpringBoot简单使用(1)
    1:xml文件与javaconfig 1.1.1什么是javaconfig:是spring提供的使用java类配置容器。配置springIOC容器的纯java方法优点:可以使用面向对象的方式,一个配置类可以继承配置......
  • 轻量级SpringBoot Office文档在线预览框架
    框架简介介绍:基于开源项目KkFileView源码提取出,封装成仅用于Office文档预览(格式转换)功能的一个通用组件;原理是把Word转成PDF,PPT转成PDF,Excel转成HTML;利用浏览......
  • Linux基础知识(14)- Docker (七) | 使用 Docker 部署 SpringBoot 项目
    本文将完全复制“Springboot基础知识(08)-spring-boot-starter-web(Web启动器)”里的SpringbootWeb项目的代码和配置到新项目SpringbootWebDocker。在新项目Springboot......