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

这篇具有很好参考价值的文章主要介绍了springboot 与异步任务,定时任务,邮件任务。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

异步任务

在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 与异步任务,定时任务,邮件任务,# SpringBoot,spring boot,后端,java
访问看到控制台打印顺序可以知道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 与异步任务,定时任务,邮件任务,# SpringBoot,spring boot,后端,java
springboot 与异步任务,定时任务,邮件任务,# SpringBoot,spring boot,后端,java

 /**
     * 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 与异步任务,定时任务,邮件任务,# SpringBoot,spring boot,后端,java
所以我们要是使用qq邮箱发送必须有登录qq邮箱的权限
springboot 与异步任务,定时任务,邮件任务,# SpringBoot,spring boot,后端,java
开启smtp服务,发送短信我们就可以获取一个授权码,自己拷贝下来下图的授权码记录下来
springboot 与异步任务,定时任务,邮件任务,# SpringBoot,spring boot,后端,java
springboot 与异步任务,定时任务,邮件任务,# SpringBoot,spring boot,后端,java

开始

添加依赖

<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样式。

最后代码附件文章来源地址https://www.toymoban.com/news/detail-692154.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("wufagang@dhcc.com.cn","测试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("wufagang@dhcc.com.cn","这是一封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("wufagang@dhcc.com.cn","这是一封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("wufagang@dhcc.com.cn","这是一封图片邮件",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("ispringboot@163.com","这是一封HTML模板邮件",emailContent);

    }
}

到了这里,关于springboot 与异步任务,定时任务,邮件任务的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【SpringBoot篇】Spring_Task定时任务框架

    Spring Task 是 Spring 框架提供的一种任务调度和异步处理的解决方案。 可以按照约定的时间自动执行某个代码逻辑 它可以帮助开发者在 Spring 应用中轻松地实现定时任务、异步任务等功能,提高应用的效率和可维护性。 Spring Task 的主要特点包括: 简单易用:Spring Task 提供了简

    2024年02月04日
    浏览(32)
  • springboot 发送邮件,以及邮件工具类 并且解决spring-boot-starter-mail 发送邮件附件乱码或者文件错乱

    1、设置系统值 System.setProperty(“mail.mime.splitlongparameters”, “false”); 2、 在创建对象的时候定义编码格式(utf-8): MimeMessageHelper helper = new MimeMessageHelper(mes, true, “utf-8”); 3、 其次,在添加附件的时候,附件名是需要定义编码的 helper.addAttachment(MimeUtility.encodeWord(附件名,“utf-8”

    2024年02月15日
    浏览(45)
  • Spring Boot异步任务、异步消息

    目录 1.异步任务 1.1.概述 1.2.使用 2.异步消息 2.1.概述 2.2.使用 举一个例子,我现在有一个网上商城,客户在界面点击下单后,后台需要完成两步: 1.创建客户订单 2.发短信通知客户订单号 这里面第2步是个高耗时的操作,如果全部挤在一条主线程里做,效果就会是客户点了一

    2023年04月22日
    浏览(40)
  • Spring Schedule:Spring boot整合Spring Schedule实战讲解定时发送邮件的功能

    🎉🎉 欢迎光临,终于等到你啦 🎉🎉 🏅我是 苏泽 ,一位对技术充满热情的探索者和分享者。🚀🚀 🌟持续更新的专栏 《Spring 狂野之旅:从入门到入魔》 🚀 本专栏带你从Spring入门到入魔   这是苏泽的个人主页可以看到我其他的内容哦👇👇 努力的苏泽 http://suzee.blog.

    2024年03月14日
    浏览(96)
  • java中定时任务 schedule 分布式下没有锁住 时间不同步 执行滞后 相对时间 系统时间 spring springboot

    java.util.Timer计时器可以进行:管理任务延迟执行(“如1000ms后执行任务”),及周期性执行(“如每500ms执行一次该任务”)。 但是,Timer存在一些缺陷,应考虑使用ScheduledThreadPoolExecutor代替,Timer对调度的支持是基于绝对时间,而不是相对时间的,由此任务对系统时钟的改变是敏感

    2024年02月10日
    浏览(37)
  • Spring Boot定时任务

    目录 1.概述 2.Spring Boot定时任务 2.1.快速使用 2.2.cron表达式 3.业务示例 3.1.业务描述 3.2.业务实现 4.实现原理 5.自定义线程池 在某些业务场景中,需要定时执行一些任务,有可能是定时统计然后生成报表,有可能是定时发起一个任务。最近在工作中就正好遇见一个定时发起问卷

    2024年02月07日
    浏览(38)
  • Spring boot开启定时任务

       使用@Scheduled 注解很方便,但缺点是当我们调整了执行周期的时候,需要重启应用才能生效,这多少有些不方便。为了达到实时生效的效果,那么可以使用接口来完成定时任务,统一将定时器信息存放在数据库中。 1. 在mysql中执行一下脚本插入定时任务: 2. Mapper层 3. 

    2024年02月10日
    浏览(29)
  • Spring Boot动态设置定时任务

            spring boot项目实现定时任务,最简单的一种就是基于注解 @Schedule 的方式,在启动类上添加 @EnableScheduling 注解进行标注,就可实现。但是,这个方式有个缺点,那就是执行周期写死在代码里,无法动态改变,想要改变只能修改代码再重新部署启动。为了能够动态的

    2024年02月08日
    浏览(36)
  • 解密Spring Boot的定时任务

    大家好!欢迎来到本篇博客,今天我们将深入探讨Spring Boot中的定时任务,以及它在单线程和多线程环境下的运行机制。本文将详细解析定时任务的工作原理,并附带实际案例进行演示。 1. Spring Boot定时任务的基本概念 Spring Boot的定时任务是基于Quartz Scheduler实现的,它允许您

    2024年01月19日
    浏览(40)
  • Spring Boot 面试题——定时任务

    (1)定时任务是一种 在指定的时间点或时间间隔内自动触发执行的任务 。它能够周期性地执行一些重复性、时间敏感或计划性的操作,而无需人工干预。定时任务的需求主要有以下几个方面: 自动化 :定时任务可以实现某些操作的自动化,无需人工手动执行。这可以提高

    2024年02月08日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包