SpringBoot整合Quartz以及异步调用
创始人
2024-05-30 18:47:36
0

文章目录

  • 前言
  • 一、异步方法调用
    • 1、导入依赖
    • 2、创建异步执行任务线程池
    • 3、创建业务层接口和实现类
    • 4、创建业务层接口和实现类
  • 二、测试定时任务
    • 1.导入依赖
    • 2.编写测试类,开启扫描定时任务
    • 3.测试
  • 三、实现定时发送邮件案例
    • 1.邮箱开启IMAP服务
    • 2.导入依赖
    • 3.导入EmailUtil
    • 4.编写邮件发送方法
    • 5.开启异步和定时任务
  • 总结


前言

Quartz是一个完全由java编写的开源作业调度框架、它的简单易用受到业内人士的一致好评。本篇记录怎么用SpringBoot使用Quartz


一、异步方法调用

由于多个任务同时执行时,默认为单线程,所以我们用异步方法调用,使其成为多线程执行

看一个案例

1、导入依赖

 org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-devtoolsruntimetrueorg.springframework.bootspring-boot-configuration-processortrueorg.projectlomboklomboktrueorg.springframework.bootspring-boot-starter-testtest

2、创建异步执行任务线程池

这里我们使用springboot自带的线程池

package com.lzl.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;@Configuration
public class AsyncExcutorPoolConfig implements AsyncConfigurer {@Bean("asyncExecutor")@Overridepublic Executor getAsyncExecutor() {//Spring自带的线程池(最常用)ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();//线程:IO密集型 和 CPU密集型//线程设置参数taskExecutor.setCorePoolSize(8);//核心线程数,根据电脑的核数taskExecutor.setMaxPoolSize(16);//最大线程数一般为核心线程数的2倍taskExecutor.setWaitForTasksToCompleteOnShutdown(true);//任务执行完成后关闭return taskExecutor;}
}

注意注解不要少

3、创建业务层接口和实现类

package com.lzl.Service;/*** --效率,是成功的核心关键--** @Author lzl* @Date 2023/3/7 09:42*/public interface AsyncService {void testAsync1();void testAsync2();
}
package com.lzl.Service.impl;import com.lzl.Service.AsyncService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;/*** --效率,是成功的核心关键--** @Author lzl* @Date 2023/3/7 09:43*/
@Service
public class AsyncImpl implements AsyncService {@Async@Overridepublic void testAsync1() {try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("精准是唯一重要的标准!");}@Async("asyncExecutor")//开启异步执行@Overridepublic void testAsync2() {try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("效率是成功的核心关键!");}
}

4、创建业务层接口和实现类

package com.lzl.task;import com.lzl.Service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** --效率,是成功的核心关键--** @Author lzl* @Date 2023/3/7 09:40*/
@RestController
@RequestMapping("/login")
public class LoginController {@Autowiredprivate AsyncService service;@RequestMapping("/Async1")public String testAsync1(){service.testAsync1();return "牛逼!";}@RequestMapping("/Async2")public String testAsync2(){service.testAsync2();return "不牛逼!";}
}

在启动类开启异步
在这里插入图片描述

整体目录结构如下:
在这里插入图片描述

测试:
运行项目,访问controller

在这里插入图片描述
访问controller时,页面直接出现返回值,控制台过了两秒打印文字,证明异步执行成功!
在这里插入图片描述

二、测试定时任务

1.导入依赖

		org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-devtoolsruntimetrueorg.springframework.bootspring-boot-configuration-processortrueorg.projectlomboklomboktrueorg.springframework.bootspring-boot-starter-testtest

2.编写测试类,开启扫描定时任务

package com.lzl.task;import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;import java.util.Date;/*** --效率,是成功的核心关键--** @Author lzl* @Date 2023/3/7 10:42*/
//任务类
@Configuration
public class Tasks {@Async@Scheduled(cron = "*/2 * * * * ?")public void task1(){System.out.println("效率"+new Date().toLocaleString());}@Async@Scheduled(cron = "*/1 * * * * ?")public void task2(){System.out.println("精准"+new Date().toLocaleString());}
}

在这里插入图片描述

3.测试

在这里插入图片描述

三、实现定时发送邮件案例

这里以QQ邮箱为例,这个功能类似于通过邮箱找回密码类似,需要我们进行授权码操作

1.邮箱开启IMAP服务

登陆QQ邮箱,找到帐户,下拉
在这里插入图片描述
看到如下图:
在这里插入图片描述
我这里已经开启了,按照步骤操作,会有一个授权码,保存好下边步骤要用,此处不再演示

2.导入依赖

		org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-mailorg.springframework.bootspring-boot-devtoolsruntimetrueorg.springframework.bootspring-boot-configuration-processortrueorg.projectlomboklomboktrueorg.springframework.bootspring-boot-starter-testtest

3.导入EmailUtil

package com.lzl.utils;import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Random;
/*** --效率,是成功的核心关键--** @Author lzl* @Date 2023/3/7 11:44*/public class EmailUtil {private static final String USER = "@qq.com"; // 发件人邮箱地址private static final String PASSWORD = ""; // qq邮箱的客户端授权码(需要发短信获取)/*** @param to    收件人邮箱地址* @param text  邮件正文* @param title 标题*//* 发送验证信息的邮件 */public static boolean sendMail(String to, String text, String title) {try {final Properties props = new Properties();props.put("mail.smtp.auth", "true");props.put("mail.smtp.host", "smtp.qq.com");// 发件人的账号props.put("mail.user", USER);//发件人的密码props.put("mail.password", PASSWORD);// 构建授权信息,用于进行SMTP进行身份验证Authenticator authenticator = new Authenticator() {@Overrideprotected PasswordAuthentication getPasswordAuthentication() {// 用户名、密码String userName = props.getProperty("mail.user");String password = props.getProperty("mail.password");return new PasswordAuthentication(userName, password);}};// 使用环境属性和授权信息,创建邮件会话Session mailSession = Session.getInstance(props, authenticator);// 创建邮件消息MimeMessage message = new MimeMessage(mailSession);// 设置发件人String username = props.getProperty("mail.user");InternetAddress form = new InternetAddress(username);message.setFrom(form);// 设置收件人InternetAddress toAddress = new InternetAddress(to);message.setRecipient(Message.RecipientType.TO, toAddress);// 设置邮件标题message.setSubject(title);// 设置邮件的内容体message.setContent(text, "text/html;charset=UTF-8");// 发送邮件Transport.send(message);return true;} catch (Exception e) {e.printStackTrace();}return false;}//随机生成num个数字验证码public static String getValidateCode(int num) {Random random = new Random();String validateCode = "";for (int i = 0; i < num; i++) {//0 - 9 之间 随机生成 num 次int result = random.nextInt(10);validateCode += result;}return validateCode;}//测试public static void main(String[] args) throws Exception {//给指定邮箱发送邮件EmailUtil.sendMail("729953102@qq.com", "你好,这是一封测试邮件,无需回复。", "测试邮件随机生成的验证码是:" + getValidateCode(6));System.out.println("发送成功");}
}

4.编写邮件发送方法

package com.lzl.task;import com.lzl.utils.EmailUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;/*** --效率,是成功的核心关键--** @Author lzl* @Date 2023/3/7 11:45*/
@Configuration
public class TaskEmail {//指定时间进行发送邮件@Scheduled(cron = "10 49 11 * * ?")public void sendMail(){EmailUtil.sendMail("自己的邮箱@qq.com", "效率,是成功的核心关键!", "测试邮件随机生成的验证码是:" + EmailUtil.getValidateCode(6));}
}

5.开启异步和定时任务

package com.lzl;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication
@EnableAsync//开启异步
@EnableScheduling//开启定时任务
public class QuartzStudyApplication {public static void main(String[] args) {SpringApplication.run(QuartzStudyApplication.class, args);}}

测试:
此处不再演示


总结

定时任务在很多业务场景中经常会用到,好记性不如烂笔头,本篇只是简单的记录一下

相关内容

热门资讯

自动打开应用安卓系统,安卓系统... 你有没有想过,手机里的那些应用,有时候真是让人又爱又恨呢?有时候,我们急需某个应用,却得费老大力气去...
安卓系统防沉迷软件,守护青少年... 你有没有发现,现在手机上玩游戏的诱惑力简直让人无法抗拒?尤其是安卓系统,那丰富的游戏资源,简直让人停...
流量最快的安卓系统,揭秘流量最... 你有没有想过,为什么你的手机总是那么卡,而别人的手机却像开了挂一样流畅?是不是好奇,为什么有些安卓系...
小米5换换安卓系统,畅享极致性... 你有没有想过,你的小米5手机,那个陪伴你走过无数日夜的小家伙,是不是也该给它来个“换新装”了呢?没错...
国产的安卓系统手机,畅享智能生... 你有没有发现,最近国产的安卓系统手机越来越火了?没错,就是那种咱们自己研发的系统,那种让外国品牌都不...
安卓系统刷入停止,探究原因与解... 你有没有遇到过这种情况?手机刷机过程中突然停止了,安卓系统刷入停滞不前,心里那个急啊!别慌,今天就来...
汽车是安卓系统嘛,安卓系统在智... 你有没有想过,汽车里那个神奇的操作系统,是不是和安卓手机里的一样呢?没错,今天咱们就来聊聊这个话题—...
网易狼人杀 安卓系统,体验指尖... 亲爱的玩家们,你是否曾在深夜里,手机屏幕前,与一群好友展开一场惊心动魄的“狼人杀”对决?今天,就让我...
小米安卓系统小主机,探索小米安... 你有没有想过,家里的电视、电脑、平板,甚至手机,其实都可以变成一个超级智能的娱乐中心?没错,这就是小...
卡刷安卓系统大全,全面解析各类... 你有没有想过,你的安卓手机可以像变形金刚一样,随心所欲地变换模样?没错,今天就要给你揭秘一个神奇的世...
安卓系统测试流畅度,安卓系统流... 你有没有发现,现在手机更新换代的速度简直就像坐上了火箭呢!尤其是安卓系统,每次更新都让人眼前一亮。但...
安卓系统50怎么升级,轻松迈向... 亲爱的安卓用户们,你是否也像我一样,对安卓系统的更新充满了期待?没错,就是那个让我们的手机焕然一新的...
安卓5.1.1操作系统,系统特... 你知道吗?在手机世界里,操作系统就像是个大管家,它不仅决定了手机的脸面,还掌管着手机的所有“家务事”...
手机安卓系统如果升级,体验流畅... 亲爱的手机控们,你们有没有发现,你的安卓手机最近是不是总在提醒你更新系统呢?别急,别急,今天就来给你...
安卓系统怎么禁止待机,安卓系统... 手机待机时间短,是不是让你头疼不已?别急,今天就来教你一招,让你的安卓手机告别“短命”模式,延长待机...
亿联安卓苹果系统,跨平台沟通新... 你知道吗?在科技飞速发展的今天,手机操作系统可是咱们日常生活中不可或缺的一部分。说起手机系统,亿联安...
smoothx安卓系统安装ap... 你有没有想过,为什么你的手机里总是乱糟糟的,各种app堆在一起,找起来费劲得很?别急,今天就来教你怎...
安卓系统图库在哪里,图库应用位... 你有没有发现,手机里的照片越来越多,有时候想找一张特定的照片,却像大海捞针一样困难?别急,今天就来告...
安卓7.0系统自带彩蛋,隐藏彩... 你知道吗?安卓7.0系统里竟然藏着不少小秘密,就像一颗颗隐藏的彩蛋,等着我们去发现。今天,就让我带你...
安卓系统好用的电池,好用到飞起... 你有没有发现,用安卓手机的时候,电池续航能力简直让人爱不释手啊!没错,今天咱们就来聊聊这个话题——安...