• 28-SpringBoot 异步任务、定时任务、邮件任务


    1.异步任务

    1.在主类或者配置类上使用@EnableAsync注解开启异步任务

    @SpringBootApplication
    @MapperScan(basePackages = "com.limi.springboottest2.mapper")
    @EnableAsync  //开启异步任务
    public class SpringbootTest2Application {
    ;
        public static void main(String[] args) {
    
            //1、返回我们IOC容器
            ConfigurableApplicationContext run = SpringApplication.run(SpringbootTest2Application.class, args);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    2.编写异步任务

    package com.limi.springboottest2.service;
    
    
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Service;
    
    @Service
    public class AsyncService {
    
        @Async
        public void say(){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("异步任务处理中...");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    3.测试执行

    
        @Autowired
        private AsyncService asyncService;
    
    
        @ResponseBody
        @GetMapping("/test1")
        public String test(){
            asyncService.say();
            return "ok";
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    访问立即得到返回数据
    在这里插入图片描述
    在这里插入图片描述

    2.定时任务

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

    在这里插入图片描述

    1.在配置类或者启动类上使用@EnableScheduling注解开启定时任务

    package com.limi.springboottest2;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ConfigurableApplicationContext;
    import org.springframework.scheduling.annotation.EnableScheduling;
    
    
    @SpringBootApplication
    @MapperScan(basePackages = "com.limi.springboottest2.mapper")
    @EnableScheduling  //开启定时任务
    public class SpringbootTest2Application {
    ;
        public static void main(String[] args) {
    
            //1、返回我们IOC容器
            ConfigurableApplicationContext run = SpringApplication.run(SpringbootTest2Application.class, args);
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    2.编写定时任务

    package com.limi.springboottest2.service;
    
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Service;
    
    @Service
    public class ScheduleService {
    
    
        @Scheduled(cron = "0/5 * * * * ? ") //每 5s 执行一次
        public void test(){
            System.out.println("ok");
        }
    }
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    cron表达式可使用在线生成器生成, 生成器网址

    在这里插入图片描述

    3.运行测试
    在这里插入图片描述

    3.邮件任务

    • 邮件发送需要引入spring-boot-starter-mail
    • Spring Boot 自动配置MailSenderAutoConfiguration
    • 定义MailProperties内容,配置在application.yml中 • 自动装配JavaMailSender
    • 测试邮件发送

    开启QQ邮箱授权码
    在这里插入图片描述
    在这里插入图片描述

    ryazxwcwiwjubjab

    1.添加依赖

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-mail</artifactId>
            </dependency>
    
    • 1
    • 2
    • 3
    • 4

    2.编写配置

    #发送邮件服务器
    spring.mail.host=smtp.qq.com
    #邮箱账号
    spring.mail.username=limimail@qq.com
    #邮箱授权码
    spring.mail.password=ryaabccwiwjubjab
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    3.编写代码

    邮件服务类MailService

    package com.limi.springboottest2.service;
    
    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;
    
    @Service
    public class MailService {
        private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
        @Autowired
        private JavaMailSender javaMailSender;
    
        //注入配置文件中配置的信息username——>from
        @Value("${spring.mail.username}")
        private String from;
    
        //简单邮件
        public void sendSimpleMail(String to, String subject, String content) {
            SimpleMailMessage message = new SimpleMailMessage();
            //发件人
            message.setFrom(from);
            //收件人
            message.setTo(to);
            //邮件主题
            message.setSubject(subject);
            //邮件内容
            message.setText(content);
            //发送邮件
            javaMailSender.send(message);
        }
    
    
        //html邮件
        public void sendHtmlMail(String to, String subject, String content) {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper;
            try {
                messageHelper = new MimeMessageHelper(message,true);
                messageHelper.setFrom(from);
                messageHelper.setTo(to);
                message.setSubject(subject);
                messageHelper.setText(content,true);
                javaMailSender.send(message);
                logger.info("邮件已经发送!");
            } catch (MessagingException e) {
                logger.error("发送邮件时发生异常:"+e);
            }
        }
    
        //带附件邮件
        public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper;
            try {
                messageHelper = new MimeMessageHelper(message,true);
                messageHelper.setFrom(from);
                messageHelper.setTo(to);
                messageHelper.setSubject(subject);
                messageHelper.setText(content,true);
                //携带附件
                FileSystemResource file = new FileSystemResource(filePath);
                String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
                messageHelper.addAttachment(fileName,file);
    
                javaMailSender.send(message);
                logger.info("邮件加附件发送成功!");
            } catch (MessagingException e) {
                logger.error("发送失败:"+e);
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83

    测试类MyTest

    package com.limi.springboottest2;
    
    
    import com.limi.springboottest2.service.MailService;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    
    
    @SpringBootTest
    
    public class MyTest {
    
        @Autowired
        private MailService emailService;
    
        @Test
        public void sendSimpleEmail(){
            String content = "你好,恭喜你...";
            emailService.sendSimpleMail("lmail123@163.com","祝福邮件",content);
        }
    
        @Test
        public void sendMimeEmail(){
            String content = "<a href='https://blog.csdn.net/'>你好,欢迎注册网站,请点击链接激活</a>";
            emailService.sendHtmlMail("lmail123@163.com","激活邮件",content);
        }
    
        @Test
        public void sendAttachment(){
            emailService.sendAttachmentsMail("lmail123@163.com","发送附件","Spring体系图","E:\\Office文档\\tu\\3.jpg");
        }
    
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    测试结果
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

  • 相关阅读:
    Hive引擎MR、Tez、Spark
    【ROS2原理19】定时器模型
    卓越领先!安全狗入选2023年福建省互联网综合实力50强
    一级造价工程师(安装)- 计量笔记 - 第五章第二节通风空调工程
    JavaScript | 详解变量作用域
    MySQL数据行怎么转为列
    SQL每日一练(牛客新题库)——第3天: 条件查询
    双飞翼布局
    【Java 基础篇】自如应对文本数据:Java缓冲字符流详解
    CentOS7.9中使用packstack安装train版本
  • 原文地址:https://blog.csdn.net/qq_41865229/article/details/125605839