SpringBoot使用Quartz定时器实现Email信息轰炸

1、SpringBoot集成Quartz

1.Quartz简介

Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,它可以与J2EE与J2SE应用程序相结合也可以单独使用。Quartz可以用来创建简单或为运行十个,百个,甚至是好几万个Jobs这样复杂的程序。Jobs可以做成标准的Java组件或 EJBs。 (百度百科)

2.引入依赖

        <!-- quartz 定时器 -->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.3</version>
        </dependency>

3.两种方法配置定时器

第一种:

在 resources 下配置 spring-mvc.xml
代码如下:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.2.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/task
       http://www.springframework.org/schema/task/spring-tack.xsd
       ">

    <context:annotation-config/>
        <!-- 利用 import 引入定时器的文件 -->
    <import resource="spring-quartz.xml"/>

</beans>

在 resources 下配置 spring-quartz.xml
代码如下:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       ">
    <!-- 定义Job对象 -->
    <bean id="taskJob" class="com.example.demojpa.quartz.TestTask"/>
    <!--  定义JobDetail 对象 -->
    <bean id="JobDetail"
          class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <!-- 目标对象tackJob -->
        <property name="targetObject">
            <ref bean="taskJob"/>
        </property>
        <!-- 目标方法 -->
        <property name="targetMethod">
            <value>run</value>
        </property>
    </bean>

    <!-- 调度触发器 -->
    <bean id="myTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <!-- 指定使用jobDetail -->
        <property name="jobDetail">
            <ref bean="JobDetail"/>
        </property>
        <!-- 定义触发规则,每60秒执行一次 -->
        <property name="cronExpression">
            <value>0/60 * * * * ?</value>
        </property>
    </bean>

    <!-- 调度工厂 -->
    <bean id="schedules" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <!-- 注册触发器,可注册多个 -->
        <property name="triggers">
            <list>
                <ref bean="myTrigger"/>
            </list>
        </property>
    </bean>
</beans>

在与service同级的目录下创建文件夹quartz,在里面创建一个类TestTask
代码如下:

package com.example.demojpa.quartz;

import org.apache.logging.log4j.*;
/*
* 定时器类
* ye
* 2020.10.27
* */
public class TestTask {
    //日志对象
    private static final Logger logger = LogManager.getLogger(TestTask.class);

    public void run(){
        logger.info("定时器运行了!!!");
    }
}

第二种:

在 resources 下配置 spring-mvc.xml
代码如下:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.2.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/task
       http://www.springframework.org/schema/task/spring-tack.xsd
       ">

    <context:annotation-config/>
        <!-- 利用 import 引入定时器的文件 -->
    <import resource="spring-quartz.xml"/>

</beans>

在与service同级的目录下创建文件夹quartz,在里面创建一个类SendMailQuartz
代码如下:

package com.example.demojpa.quartz;

import com.example.demojpa.mail.SendJunkMailService;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.apache.logging.log4j.*;
import com.example.demojpa.service.AyUserService;
import javax.annotation.Resource;
import java.util.List;
import com.example.demojpa.model.AyUser;
/*
* 定时器
* ye
* 2020.10.27
*
* */
@Component
@Configurable
@EnableScheduling
public class SendMailQuartz {

    //日志对象
    private static final Logger logger = LogManager.getLogger(SendMailQuartz.class);

    //每60秒执行一次
    @Scheduled(cron = "*/60 * * * *  *")
    public void reportCurrentByCron(){
        logger.info("定时器运行了!!!");
    }
}

同时在入口类,xxxApplication 加入@ImportResource注解

@SpringBootApplication
@ServletComponentScan
@ImportResource(locations = {"classpath:spring-mvc.xml"})
public class DemojpaApplication {

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

}

4.测试

我是两种方法一起测试的
在这里插入图片描述
运行成功!

2、使用Quartz实现Email信息轰炸

1.引入Mail的依赖

在pom.xml加入以下依赖

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

2.添加配置

在application.properties中加入相关配置

### Mail邮件配置
### 邮箱主机
spring.mail.host=smtp.qq.com
### 用户名(你要登录的邮箱)
spring.mail.username=xxxx@qq.com
### 设置授权码
spring.mail.password=xxxx

### 默认编码
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties..mail.smtp.starttls.enable=true
spring.mail.properties..mail.smtp.starttls.required=true

3.在quartz中发生邮件

第一步:
在于service同级的目录下创建mail文件夹,新建接口服务类SendJunkMailService,代码如下:

package com.example.demojpa.mail;
import java.util.List;
import com.example.demojpa.model.AyUser;
/*
* 发送用户邮件服务接口
* ye
* 2020.10.28
* */
public interface SendJunkMailService {
    //AyUser的作用只是为了获取名字,可以省略
    boolean sendJunkMail(List<AyUser> ayUsers);
}

第二步:
继续在该文件夹加新建以下impl文件夹,并新建实现类SendJunkMailServiceImpl,代码如下:

package com.example.demojpa.mail.impl;

import com.example.demojpa.mail.SendJunkMailService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import com.example.demojpa.service.AyUserService;
import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.List;
import com.example.demojpa.model.AyUser;
/*
* 发送邮件服务接口实现
* ye
* 2020.10.28
* */
@Service
public class SendJunkMailServiceImpl implements SendJunkMailService {
    @Autowired
    JavaMailSender mailSender;

    @Resource
    private AyUserService ayUserService;

    @Value("${spring.mail.username}")
    private String from;
    public static final Logger logger = LogManager.getLogger(SendJunkMailServiceImpl.class);

    @Override
    public boolean sendJunkMail(List<AyUser> ayUserList){
        try{
            if (ayUserList==null||ayUserList.size()<=0) return Boolean.FALSE;
            for (AyUser ayUser:ayUserList){
                MimeMessage mimeMessage = this.mailSender.createMimeMessage();
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                //邮件发送方
                message.setFrom(from);
                //邮件主题
                message.setSubject("录用通知");
                //邮件接收方
                message.setTo("xxxxx@qq.com");
                //邮件内容
                message.setText("恭喜您, "+ ayUser.getName() + ",您被录用了!");
                //发送邮件
                this.mailSender.send(mimeMessage);
            }
        }catch (Exception e){
            logger.error("sendJunkMail error and ayUser=%s",ayUserList,e);
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }
}

第三步:
在我们开发的SendMailQuartz做一些修改:

package com.example.demojpa.quartz;

import com.example.demojpa.mail.SendJunkMailService;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.apache.logging.log4j.*;
import com.example.demojpa.service.AyUserService;
import javax.annotation.Resource;
import java.util.List;
import com.example.demojpa.model.AyUser;
/*
* 定时器
* ye
* 2020.10.27
*
* */
@Component
@Configurable
@EnableScheduling
public class SendMailQuartz {

    //日志对象
    private static final Logger logger = LogManager.getLogger(SendMailQuartz.class);

    @Resource
    private SendJunkMailService sendJunkMailService;

    @Resource
    private AyUserService ayUserService;

    //每60秒执行一次
    @Scheduled(cron = "*/60 * * * *  *")
    public void reportCurrentByCron(){
        List<AyUser> userList = ayUserService.findAll();
        if (userList == null || userList.size() <= 0) return;;
        //发送邮件
        sendJunkMailService.sendJunkMail(userList);
        logger.info("定时器运行了!!!");
    }
}

4.测试

在这里插入图片描述
我另一个邮箱收到了自己发送的邮件,成功!

©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页