首页 > 其他分享 >springboot 与异步任务,定时任务,邮件任务

springboot 与异步任务,定时任务,邮件任务

时间:2023-10-01 14:03:50浏览次数:34  
标签:异步 springboot param 任务 contnet subject public 邮件 String


异步任务

在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的;但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,其实,在Spring 3.x之后,就已经内置了@Async来完美解决这个问题。

SpringBoot 实现比较简单
主启动类:添加 注释:@EnableAsync

@EnableScheduling
@EnableAsync
@MapperScan("com.hrp.**.dao")
@SpringBootApplication
public class EcsApplication {
    public static void main(String[] args) {
        SpringApplication.run(EcsApplication.class, args);
    }

}

业务方法添加 @Async

@Async
    @Override
    public void TestAsync() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("-------------");
    }

controller调用

@RequestMapping("myFreeMark")
    public String myFreeMark(Map<String,Object> map){
        map.put("name","zhangsan");
        map.put("mydate",new Date());
        asyncServer.TestAsync();
        System.out.println("==================FreemarkerController=======myFreeMark=====");
        return "myFreeMark";
    }

springboot 与异步任务,定时任务,邮件任务_spring boot


访问看到控制台打印顺序可以知道TestAsync方法异步调用

定时任务

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

主启动类:增加@EnableScheduling

@EnableScheduling
@EnableAsync
@MapperScan("com.hrp.**.dao")
@SpringBootApplication
public class EcsApplication {
    public static void main(String[] args) {
        SpringApplication.run(EcsApplication.class, args);
    }

}

任务类:类增加@Service或者@Compont注释方法增加@Scheduled注解

@Service
public class BackUpMysqlTask {

    /**
     * Seconds : 可出现", - * /"四个字符,有效范围为0-59的整数
     * Minutes : 可出现", - * /"四个字符,有效范围为0-59的整数
     * Hours : 可出现", - * /"四个字符,有效范围为0-23的整数
     * DayofMonth : 可出现", - * / ? L W C"八个字符,有效范围为0-31的整数
     * Month : 可出现", - * /"四个字符,有效范围为1-12的整数或JAN-DEc
     * DayofWeek : 可出现", - * / ? L C #"四个字符,有效范围为1-7的整数或SUN-SAT两个范围。1表示星期天,2表示星期一, 依次类推
     * Year : 可出现", - * /"四个字符,有效范围为1970-2099年
     */
    @Scheduled(cron = "0 * * * * MON-FRI")
    public void backUpMysql() {
        System.out.println("===============");
    }
}

我们可以观察到控制台不断的再打印
这里要讲解cron

springboot 与异步任务,定时任务,邮件任务_HTML_02


springboot 与异步任务,定时任务,邮件任务_spring_03

/**
     * Seconds : 可出现", - * /"四个字符,有效范围为0-59的整数
     * Minutes : 可出现", - * /"四个字符,有效范围为0-59的整数
     * Hours : 可出现", - * /"四个字符,有效范围为0-23的整数
     * DayofMonth : 可出现", - * / ? L W C"八个字符,有效范围为0-31的整数
     * Month : 可出现", - * /"四个字符,有效范围为1-12的整数或JAN-DEc
     * DayofWeek : 可出现", - * / ? L C #"四个字符,有效范围为1-7的整数或SUN-SAT两个范围。1表示星期天,2表示星期一, 依次类推
     * Year : 可出现", - * /"四个字符,有效范围为1970-2099年
     */

下面简单举几个例子:

“0 0 12 * * ?” 每天中午十二点触发
“0 15 10 ? * *” 每天早上10:15触发
“0 15 10 * * ?” 每天早上10:15触发
“0 15 10 * * ? *” 每天早上10:15触发
“0 15 10 * * ? 2005” 2005年的每天早上10:15触发
“0 * 14 * * ?” 每天从下午2点开始到2点59分每分钟一次触发
“0 0/5 14 * * ?” 每天从下午2点开始到2:55分结束每5分钟一次触发
“0 0/5 14,18 * * ?” 每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发
“0 0-5 14 * * ?” 每天14:00至14:05每分钟一次触发
“0 10,44 14 ? 3 WED” 三月的每周三的14:10和14:44触发
“0 15 10 ? * MON-FRI” 每个周一、周二、周三、周四、周五的10:15触发

邮件任务

准备工作

做过邮件的都大家都知道

springboot 与异步任务,定时任务,邮件任务_java_04


所以我们要是使用qq邮箱发送必须有登录qq邮箱的权限

springboot 与异步任务,定时任务,邮件任务_HTML_05


开启smtp服务,发送短信我们就可以获取一个授权码,自己拷贝下来下图的授权码记录下来

springboot 与异步任务,定时任务,邮件任务_java_06


springboot 与异步任务,定时任务,邮件任务_后端_07

开始

添加依赖

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

配置

mail:
    host: smtp.qq.com  其他邮箱需要修改
    username: 邮箱账户
    password: 授权码
    properties:
      mail:
        smtp:
          ssl:
            enable: true

测试代码

@Autowired
    private JavaMailSender javaMailSender;
    @Test
    void contextLoads() {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setText("ddd");
        simpleMailMessage.setSubject("主题");
        simpleMailMessage.setTo("");
        simpleMailMessage.setFrom("");
        javaMailSender.send(simpleMailMessage);
    }

我们可以查收到邮件

上面是普通的邮件

发送html内容

@Test
    public void testSend() throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setSubject("标题");
        messageHelper.setTo("@dhcc.com.cn");
        messageHelper.setFrom("@qq.com");
        messageHelper.setText("<h1>标题</h1><br/><p>这是内容</p>", true);
        javaMailSender.send(messageHelper.getMimeMessage());
    }

这里需要注意的是,setText的时候需要传一个布尔值进去,表名需要使用HTML样式。

最后代码附件

package com.hrp.msage.service;

import javax.mail.MessagingException;

/**
 * ecs
 *
 * @Title: com.hrp.msage.service
 * @Date: 2020/7/29 13:48
 * @Author: wfg
 * @Description:
 * @Version:
 */
public interface MailService {
    /**
     * 简单文本邮件
     * @param to 接收者邮件
     * @param subject 邮件主题
     * @param contnet 邮件内容
     */
    public void sendSimpleMail(String to, String subject, String contnet);
    /**
     * HTML 文本邮件
     * @param to 接收者邮件
     * @param subject 邮件主题
     * @param contnet HTML内容
     * @throws MessagingException
     */
    public void sendHtmlMail(String to, String subject, String contnet) throws MessagingException;
    /**
     * 附件邮件
     * @param to 接收者邮件
     * @param subject 邮件主题
     * @param contnet HTML内容
     * @param filePath 附件路径
     * @throws MessagingException
     */
    public void sendAttachmentsMail(String to, String subject, String contnet,
                                    String filePath) throws MessagingException;
    /**
     * 图片邮件
     * @param to 接收者邮件
     * @param subject 邮件主题
     * @param contnet HTML内容
     * @param rscPath 图片路径
     * @param rscId 图片ID
     * @throws MessagingException
     */
    public void sendInlinkResourceMail(String to, String subject, String contnet,
                                       String rscPath, String rscId);
}
package com.hrp.msage.serviceImpl;

import com.hrp.msage.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * ecs
 *
 * @Title: com.hrp.msage.serviceImpl
 * @Date: 2020/7/29 13:48
 * @Author: wfg
 * @Description:
 * @Version:
 */
@Service("mailService")
public class MailServiceImpl implements MailService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 简单文本邮件
     * @param to 接收者邮件
     * @param subject 邮件主题
     * @param contnet 邮件内容
     */
    @Override
    public void sendSimpleMail(String to, String subject, String contnet){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(contnet);
        message.setFrom(from);
        mailSender.send(message);
    }
    /**
     * HTML 文本邮件
     * @param to 接收者邮件
     * @param subject 邮件主题
     * @param contnet HTML内容
     * @throws MessagingException
     */
    @Override
    public void sendHtmlMail(String to, String subject, String contnet) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(contnet, true);
        helper.setFrom(from);

        mailSender.send(message);
    }

    /**
     * 附件邮件
     * @param to 接收者邮件
     * @param subject 邮件主题
     * @param contnet HTML内容
     * @param filePath 附件路径
     * @throws MessagingException
     */
    @Override
    public void sendAttachmentsMail(String to, String subject, String contnet,
                                    String filePath) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(contnet, true);
        helper.setFrom(from);

        FileSystemResource file = new FileSystemResource(new File(filePath));
        String fileName = file.getFilename();
        helper.addAttachment(fileName, file);

        mailSender.send(message);
    }

    /**
     * 图片邮件
     * @param to 接收者邮件
     * @param subject 邮件主题
     * @param contnet HTML内容
     * @param rscPath 图片路径
     * @param rscId 图片ID
     * @throws MessagingException
     */
    @Override
    public void sendInlinkResourceMail(String to, String subject, String contnet,
                                       String rscPath, String rscId) {
        logger.info("发送静态邮件开始: {},{},{},{},{}", to, subject, contnet, rscPath, rscId);

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;

        try {

            helper = new MimeMessageHelper(message, true);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(contnet, true);
            helper.setFrom(from);

            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);
            mailSender.send(message);
            logger.info("发送静态邮件成功!");

        } catch (MessagingException e) {
            logger.info("发送静态邮件失败: ", e);
        }

    }



}
package com.hrp;

import com.hrp.msage.service.MailService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.mail.MessagingException;

/**
 * ecs
 *
 * @Title: com.hrp
 * @Date: 2020/7/29 13:57
 * @Author: wfg
 * @Description:
 * @Version:
 */
@SpringBootTest
public class MailServiceTest {


    @Autowired
    private MailService mailService;

//    @Resource
//    private TemplateEngine templateEngine;

    @Test
    public void sendSimpleMail() {
        mailService.sendSimpleMail("[email protected]","测试spring boot imail-主题","测试spring boot imail - 内容");
    }

    @Test
    public void sendHtmlMail() throws MessagingException {

        String content = "<html>\n" +
                "<body>\n" +
                "<h3>hello world</h3>\n" +
                "<h1>html</h1>\n" +
                "<body>\n" +
                "</html>\n";

        mailService.sendHtmlMail("[email protected]","这是一封HTML邮件",content);
    }

    @Test
    public void sendAttachmentsMail() throws MessagingException {
        String filePath = "D:\\projects\\20200727\\ecs\\src\\main\\resources\\system.properties";
        String content = "<html>\n" +
                "<body>\n" +
                "<h3>hello world</h3>\n" +
                "<h1>html</h1>\n" +
                "<h1>附件传输</h1>\n" +
                "<body>\n" +
                "</html>\n";
        mailService.sendAttachmentsMail("[email protected]","这是一封HTML邮件",content, filePath);
    }

    @Test
    public void sendInlinkResourceMail() throws MessagingException {
        //TODO 改为本地图片目录
        String imgPath = "D:\\projects\\20200727\\ecs\\src\\main\\resources\\imag\\IMG_20200625_104833.jpg";
        String rscId = "admxj001";
        String content = "<html>" +
                "<body>" +
                "<h3>hello world</h3>" +
                "<h1>html</h1>" +
                "<h1>图片邮件</h1>" +
                "<img src='cid:"+rscId+"'></img>" +
                "<body>" +
                "</html>";

        mailService.sendInlinkResourceMail("[email protected]","这是一封图片邮件",content, imgPath, rscId);
    }

    @Test
    public void testTemplateMailTest() throws MessagingException {
//        Context context = new Context();
//        context.setVariable("id","ispringboot");
//
//        String emailContent = templateEngine.process("emailTeplate", context);
//        mailService.sendHtmlMail("[email protected]","这是一封HTML模板邮件",emailContent);

    }
}


标签:异步,springboot,param,任务,contnet,subject,public,邮件,String
From: https://blog.51cto.com/u_15935817/7673856

相关文章

  • 轻松完成图像处理任务的Python工具
    随着数字时代的到来,图像处理技术越来越重要。Python作为一门功能强大、易学易用的编程语言,自然也成为了图像处理领域的一把好手。Python提供了很多开源工具,可以帮助我们轻松完成各种图像处理任务。本文将介绍几种可用于图像处理的Python工具。一、PillowPillow是Python图像处理领域......
  • springboot web开发springmvc自动配置原理
    前言我们也知道springboot启用springmvc基本不用做什么配置可以很方便就使用了但是不了解原理,开发过程中遇到点问题估计就比较头疼,不管了解的深不深入,先巴拉一番再说…下面我们先看看官网…我的版本是2.3.2版本,发现官网改动也比较大…不同版本自己巴拉下吧,结构虽然变化了,但......
  • springboot web开发登录拦截器
    在SpringBoot中我们可以使用HandlerInterceptorAdapter这个适配器来实现自己的拦截器。这样就可以拦截所有的请求并做相应的处理。应用场景日志记录,可以记录请求信息的日志,以便进行信息监控、信息统计等。权限检查:如登陆检测,进入处理器检测是否登陆,如果没有直接返回到登陆页面。性......
  • SpringBoot框架大晚上报错404--我的路径问题(附上SpringBoot MVC管理系统的简单具体代
    代码application.ymlspring:web:resources:static-locations:classpath:/static/,classpath:/templates/datasource:type:com.alibaba.druid.pool.DruidDataSourceurl:jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf......
  • springboot整合mybatisPlus全技巧(1-整合过程)
    本文基于springboot整合mybatisPlus的各种文章早已烂大街的背景下,根据整合过程,MP开发中的常见技巧,MP开发中遇到的各种坑三个方面,来对这一专题做一个全面且实用的总结,基本上只要你吃透这篇文章,开发中关于mybatisplus你能遇到的问题都能迎刃而解了。整合过程网上对于springboot......
  • taskhostw.exe是Windows操作系统中的一个系统进程,主要作用是支持并调用Windows任务计
    taskhostw.exe是Windows操作系统中的一个系统进程,主要作用是支持并调用Windows任务计划程序。当您在计算机上创建或修改计划任务时,taskhostw.exe会启动并运行相应的任务。常见的任务计划包括备份、系统检查、磁盘清理等等。通过设置计划任务,可以让计算机在特定时间或事件发生时自......
  • 前端 | React setState 同步异步以及处理方式 | React
    前端|ReactsetState同步异步以及处理方式|React问题描述在同步执行流程中setState表现为异步,而在异步执行流程中setState表现为同步。示例:有一个控制DOM节点显隐的状态值,默认为false,而下一步就需要获取该DOM节点做一系类处理。所以一开始使用setState设置状态值为true,让该......
  • Java:Springboot和React中枚举值(数据字典)的使用
    目录1、开发中的需求2、实现效果3、后端代码4、前端代码5、接口数据6、完整代码7、参考文章1、开发中的需求开发和使用过程中,通常会涉及四个角色:数据库管理员、后端开发人员、前端开发人员、浏览者数据库使用int类型的数值进行存储(eg:0、1、2)Java代码使用enum枚举类型的对象进行......
  • Flutter/Dart第04天:Dart异步编程(Future和async/await)
    Dart官网代码实验室:https://dart.dev/codelabs/async-await重要说明:本博客基于Dart官网代码实验室,但并不是简单的对官网文章进行翻译,我会根据个人研发经验,在覆盖官网文章核心内容情况下,加入自己的一些扩展问题和问题演示和总结,包括名称解释、使用场景说明、代码样例覆盖、最后完......
  • java springboot项目,mybatisplus,import com.baomidou.mybatisplus.core.mapper.BaseMa
    <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.1.2</version><!--用版本2.1.9就不行,UserMapper里BaseMapper爆红--></dependency>我的结果是,......