zoukankan      html  css  js  c++  java
  • Springboot异步、定时、邮件任务

    Springboot异步、定时、邮件任务

    一、异步任务

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

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

    1、给需要多线程处理的方法添加@Async注解;

    @Service
    public class AsyncService {
        /**
         * description: 异步发送邮件
         * 使用 @Async 注解告诉Spring这是一个异步方法,SpringBoot就会自己开一个线程池,进行调用!
         */
        @Async
        public void asyncTask() {
            try {
                System.out.println("业务处理开始");
                System.out.println("业务处理进行中");
                //TODO 发送邮件
                
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            System.out.println("业务处理结束");
        }
    }
    

    2、让这个注解生效,我们还需要在主程序上添加一个注解@EnableAsync ,开启异步注解功能。

    /**
     * description: 启动器
     * 使用 @EnableAsync 开启异步注解功能
     */
    @EnableAsync
    @EnableScheduling
    @SpringBootApplication
    public class AsyncApplication {
        public static void main(String[] args) {
            SpringApplication.run(AsyncApplication.class, args);
        }
    }
    

    二、定时任务

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

    • TaskExecutor接口
    • TaskScheduler接口

    两个注解:

    • @EnableScheduling
    • @Scheduled

    cron表达式:

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

    1、在需要定时执行的方法上添加@Scheduled(cron = "cron表达式")

    /**
     * description: 定时任务
     */
    @Service
    public class ScheduledService {
        /**
         * description: 定时任务
         */
        @Scheduled(cron = "0/2 * * * * ?")
        public void timedTask() {
            //TODO 定时操作 
            
        }
    }
    

    2、在主程序上增加@EnableScheduling 开启定时任务功能

    /**
     * description: 启动器
     * 使用 @EnableScheduling 开启定时任务注解功能
     */
    @EnableScheduling
    @SpringBootApplication
    public class AsyncApplication {
        public static void main(String[] args) {
            SpringApplication.run(AsyncApplication.class, args);
        }
    }
    

    3、常用的表达式

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

    三、邮件任务

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

    @Configuration(
        proxyBeanMethods = false
    )
    @ConditionalOnClass({MimeMessage.class, MimeType.class, MailSender.class})
    @ConditionalOnMissingBean({MailSender.class})
    @Conditional({MailSenderAutoConfiguration.MailSenderCondition.class})
    @EnableConfigurationProperties({MailProperties.class})
    @Import({MailSenderJndiConfiguration.class, MailSenderPropertiesConfiguration.class})
    public class MailSenderAutoConfiguration {
        public MailSenderAutoConfiguration() {
        }
    ...
    

    进入MailSenderJndiConfiguration这个类中存在bean JavaMailSenderImpl

    @Configuration(
        proxyBeanMethods = false
    )
    @ConditionalOnClass({Session.class})
    @ConditionalOnProperty(
        prefix = "spring.mail",
        name = {"jndi-name"}
    )
    @ConditionalOnJndi
    class MailSenderJndiConfiguration {
        private final MailProperties properties;
    
        MailSenderJndiConfiguration(MailProperties properties) {
            this.properties = properties;
        }
    
        @Bean
        JavaMailSenderImpl mailSender(Session session) {
            JavaMailSenderImpl sender = new JavaMailSenderImpl();
            sender.setDefaultEncoding(this.properties.getDefaultEncoding().name());
            sender.setSession(session);
            return sender;
        }
    ...
    

    然后我们去看下ConfigurationProperties配置文件

    @ConfigurationProperties(
       prefix = "spring.mail"
    )
    public class MailProperties {
       private static final Charset DEFAULT_CHARSET;
       private String host;
       private Integer port;
       private String username;
       private String password;
       private String protocol = "smtp";
       private Charset defaultEncoding;
       private Map<String, String> properties;
       private String jndiName;
    }
    

    3、配置文件:

    spring.mail.username=xxx@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服务,具体自行查资料

    4、Spring单元测试

    @Autowired
    JavaMailSenderImpl mailSender;
    
    @Test
    public void contextLoads() {
       //邮件设置1:一个简单的邮件
       SimpleMailMessage message = new SimpleMailMessage();
       message.setSubject("通知-明天开会");
       message.setText("今晚7:30开会");
    
       message.setTo("xxx@qq.com");
       message.setFrom("xxx@qq.com");
       mailSender.send(message);
    }
    
    @Test
    public void contextLoads2() throws MessagingException {
       //邮件设置2:一个复杂的邮件
       MimeMessage mimeMessage = mailSender.createMimeMessage();
       MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    
       helper.setSubject("通知-明天开会");
       helper.setText("<b style='color:red'>今天 7:30来开会</b>",true);
    
       //发送附件
       helper.addAttachment("1.jpg",new File(""));
       helper.addAttachment("2.jpg",new File(""));
    
       helper.setTo("xxx@qq.com");
       helper.setFrom("xxx@qq.com");
    
       mailSender.send(mimeMessage);
    }
    

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

    5、异步发送邮件

    package com.sqn.service;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.mail.javamail.JavaMailSenderImpl;
    import org.springframework.mail.javamail.MimeMessageHelper;
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Service;
    
    import javax.mail.MessagingException;
    import javax.mail.internet.MimeMessage;
    import java.io.File;
    
    /**
     * description: 异步任务
     */
    @Service
    public class AsyncService {
    
        @Autowired
        JavaMailSenderImpl mailSender;
    
        /**
         * description: 异步发送邮件
         * 使用 @Async 注解告诉Spring这是一个异步方法,SpringBoot就会自己开一个线程池,进行调用!
         */
        @Async
        public void asyncTask() {
            try {
                System.out.println("业务处理开始");
                System.out.println("业务处理进行中");
                //发送一个复杂的邮件
                MimeMessage mimeMessage = mailSender.createMimeMessage();
                MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
    
                messageHelper.setSubject("通知-国庆放假");
                messageHelper.setText("国庆放假时间:10.1-10.7 ......");
    
                //发送附件
                messageHelper.addAttachment("xxx.jpg", new File("文件路径"));
                messageHelper.addAttachment("xxx.txt", new File("文件路径"));
    
                messageHelper.setTo("xxx@qq.com");
                messageHelper.setFrom("xxx@qq.com");
    
                mailSender.send(mimeMessage);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            System.out.println("业务处理结束");
        }
    }
    

    我们只需要使用Thymeleaf进行前后端结合即可开发自己网站邮件收发功能了!

    例子源码:https://gitee.com/ShiQingning/springboot-study/tree/master/async

  • 相关阅读:
    MySQL 清理slowlog方法
    MySQL定位锁争用比较严重的表
    Jvm介绍
    MyEclipse6.5的SVN插件的安装
    BASE64图片转字符串
    JDK常用工具
    Ftp服务端安装-Linux环境
    数据结构之队列
    自定义Exception异常
    基于Lua语言的触动精灵脚本开发
  • 原文地址:https://www.cnblogs.com/qingningshi/p/14833437.html
Copyright © 2011-2022 走看看