当前位置:网站首页>XXL job realizes the code parsing of email sending warnings (line by line code interpretation)
XXL job realizes the code parsing of email sending warnings (line by line code interpretation)
2022-07-24 00:26:00 【It's hard not to write code all day】
1 Relevant code location
We downloaded xxl-job Source code , To find the alarm Catalog , The code in this directory is the code related to sending warnings for the whole project ,alarm Chinese translation is a warning ;
There are only alarm There is about using email Send warning code 
2 Interface JobAlarm
There are 3 File , The first is this interface , The source code of this interface is :

Why use interfaces , Because the alarm information is predicted , Not only can we send email, And you can also send qq, WeChat , Text messages and other communications ; So just rewrite a class , Implement this interface , That's all right. , Current xxl-job, This project , Just to support email The alarm , We can expand , It is equivalent to writing an interface , It is highly expandable , Easy to maintain .
3 email Warning
We want to achieve email Warn , So write a class , Just implement the above interface ,xxl-job This project is just Support email, So in the future, we want to realize SMS by ourselves , Just write a class by yourself , Implement this interface , Just rewrite the method inside
Now read xxl-job Source code , also email Code for sending warnings :
Look at this implementation class What's inside :
Every line of code in the source code , do Commented , Look directly at the source code below
package com.xxl.job.admin.core.alarm.impl;
import com.xxl.job.admin.core.alarm.JobAlarm;
import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobLog;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.core.biz.model.ReturnT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.internet.MimeMessage;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/** * job alarm by email * Notify by email The alarm information * @author xuxueli 2020-01-19 */
@Component
public class EmailJobAlarm implements JobAlarm {
// Define the current Log object
private static Logger logger = LoggerFactory.getLogger(EmailJobAlarm.class);
/** * fail alarm * Failure alarm Logic * To begin Alarm logic * @param jobLog */
@Override
public boolean doAlarm(XxlJobInfo info, XxlJobLog jobLog){
// Define alarm result status
boolean alarmResult = true;
// send monitor email
if (info!=null && info.getAlarmEmail()!=null && info.getAlarmEmail().trim().length()>0) {
// If Task information is not empty , The alarm email is not empty
// alarmContent Alarm content
String alarmContent = "Alarm Job LogId=" + jobLog.getId(); // Log id
if (jobLog.getTriggerCode() != ReturnT.SUCCESS_CODE) {
// If The log Scheduling results You don't succeed , Content preservation Dispatch - journal
alarmContent += "<br>TriggerMsg=<br>" + jobLog.getTriggerMsg();
}
if (jobLog.getHandleCode()>0 && jobLog.getHandleCode() != ReturnT.SUCCESS_CODE) {
// If perform - state Not empty , Content preservation perform - Log specific result information
alarmContent += "<br>HandleCode=" + jobLog.getHandleMsg();
}
// email info
// According to the project id Query out actuator ( project )
XxlJobGroup group = XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao().load(Integer.valueOf(info.getJobGroup()));
// Warning message Give a person
String personal = I18nUtil.getString("admin_name_full");// The value is this : Distributed task scheduling platform XXL-JOB
// The alarm information title
String title = I18nUtil.getString("jobconf_monitor"); // The value is this : The task scheduling center monitors and alarms
// According to the template , Fill in the information
String content = MessageFormat.format(loadEmailJobAlarmTemplate(),
group!=null?group.getTitle():"null", // Project name
info.getId(), // Mission id
info.getJobDesc(),// Mission describe
alarmContent); // Alarm content
// Multiple Alarm mail
Set<String> emailSet = new HashSet<String>(Arrays.asList(info.getAlarmEmail().split(",")));
for (String email: emailSet) {
// Traverse multiple alarm messages
// make mail
try {
// Create a mail sender object
MimeMessage mimeMessage = XxlJobAdminConfig.getAdminConfig().getMailSender().createMimeMessage();
// establish Mail sending thread
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
// Get the sender of your own configuration from the configuration file The mailbox of , Sender's name
helper.setFrom(XxlJobAdminConfig.getAdminConfig().getEmailFrom(), personal);
// Who to send the mail to
helper.setTo(email);
// Sent title
helper.setSubject(title);
// Sent content
helper.setText(content, true);
// Send
XxlJobAdminConfig.getAdminConfig().getMailSender().send(mimeMessage);
} catch (Exception e) {
logger.error(">>>>>>>>>>> xxl-job, job fail alarm email send error, JobLogId:{}", jobLog.getId(), e);
alarmResult = false;
}
}
}
// Return to the alarm state ( Whether the alarm is successful , Default yes )
return alarmResult;
}
/** * load email job alarm template * Load email job alarm template ,, Front end page template * @return */
private static final String loadEmailJobAlarmTemplate(){
String mailBodyTemplate = "<h5>" + I18nUtil.getString("jobconf_monitor_detail") + ":</span>" +
"<table border=\"1\" cellpadding=\"3\" style=\"border-collapse:collapse; width:80%;\" >\n" +
" <thead style=\"font-weight: bold;color: #ffffff;background-color: #ff8c00;\" >" +
" <tr>\n" +
" <td width=\"20%\" >"+ I18nUtil.getString("jobinfo_field_jobgroup") +"</td>\n" +
" <td width=\"10%\" >"+ I18nUtil.getString("jobinfo_field_id") +"</td>\n" +
" <td width=\"20%\" >"+ I18nUtil.getString("jobinfo_field_jobdesc") +"</td>\n" +
" <td width=\"10%\" >"+ I18nUtil.getString("jobconf_monitor_alarm_title") +"</td>\n" +
" <td width=\"40%\" >"+ I18nUtil.getString("jobconf_monitor_alarm_content") +"</td>\n" +
" </tr>\n" +
" </thead>\n" +
" <tbody>\n" +
" <tr>\n" +
" <td>{0}</td>\n" +
" <td>{1}</td>\n" +
" <td>{2}</td>\n" +
" <td>"+ I18nUtil.getString("jobconf_monitor_alarm_type") +"</td>\n" +
" <td>{3}</td>\n" +
" </tr>\n" +
" </tbody>\n" +
"</table>";
return mailBodyTemplate;
}
}
4 JobAlarmer
This class , Because inheritance ApplicationContextAware, InitializingBean
These two classes , So when the project starts , Just load this class 
The function of this class is
stay JobAlarmer When the container in the class initializes, it starts from spring Get... In context
JobAlarm Class object list:jobAlarmList,( Main code :
applicationContext.getBeansOfType(JobAlarm.class);)
alarm Method jobAlarmList Call overridden doAlarm Method
( Specific implementation of alarm ), When the alarm needs to be triggered ,
Just call JobAlarmer Class alarm Method ,
All alarms can be triggered automatically , because xxl By default, only mailbox alarm ,
The code in this article only posts the email alarm EmailJobAlarm Class code ,
The advantage of this method is that when other alarm methods are needed : Such as SMS alarm ,
Just add class implementation JobAlarm Interface , Use @Component annotation ,
Rewrite method doAlarm that will do , It will be in JobAlarm Class alarm Method
jobAlarmList Trigger the SMS alarm method implemented by calling subclasses ,
Strong expandability , Easy to maintain .
The core of this class is from spring Get from the manager JobAlarm All implementation classes of the interface , in list Inside , Traverse this list, Realize alarms in various ways ;
There is only one email, because xxl-job The project of this family , Just realize this alarm
package com.xxl.job.admin.core.alarm;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/** * Context , When the project is initialized Load this */
@Component
public class JobAlarmer implements ApplicationContextAware, InitializingBean {
// Definition The current class Log object
private static Logger logger = LoggerFactory.getLogger(JobAlarmer.class);
// Context Manager
private ApplicationContext applicationContext;
// Send alarm information list
// Multiple alarm classes bean Object's aggregate
private List<JobAlarm> jobAlarmList;
/** * Set context */
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/** * Set context */
@Override
public void afterPropertiesSet() throws Exception {
// from spring Manager Inside Get Alarm class bean object
// Get... By type Multiple bean object
Map<String, JobAlarm> serviceBeanMap = applicationContext.getBeansOfType(JobAlarm.class);
if (serviceBeanMap != null && serviceBeanMap.size() > 0) {
jobAlarmList = new ArrayList<JobAlarm>(serviceBeanMap.values());
}
}
/** * job alarm * * @param info * @param jobLog * @return */
public boolean alarm(XxlJobInfo info, XxlJobLog jobLog) {
boolean result = false;
// If Multiple alarm classes bean Object's aggregate Not empty
if (jobAlarmList!=null && jobAlarmList.size()>0) {
// result = true It means All of the Call the police email issue It's all done
result = true; // success means all-success
for (JobAlarm alarm: jobAlarmList) {
// Traverse every last email Send class object
// every last email Send class object Whether the transmission is successful
boolean resultItem = false;
try {
// send out email
resultItem = alarm.doAlarm(info, jobLog);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
if (!resultItem) {
result = false;
}
}
}
return result;
}
}
边栏推荐
- Customize an object
- Gbase 8C system table information function (II)
- GBase 8c 访问权限查询函数(五)
- GBase 8c 会话信息函数(五)
- 通信模块整理(二)HC-05
- PayPal subscription process and API request
- Blockbuster | certik: Web3.0 industry safety report release in the second quarter of 2022 (PDF download link attached)
- Summary of pit websocket
- 理解多态,让不同的“人”做同一件事情会产生不同的结果
- The universal esp32c3 configures partition tables based on the Arduino ide framework
猜你喜欢

Generic mechanism and enhanced for loop

Customize an object

【电赛训练】非接触物体尺寸形态测量 2020年电赛G题

泛型机制和增强for循环

Inftnews | protect the "Snow Mountain Spirit", and the 42verse "digital ecological protection" public welfare project is about to start
![[Android kotlin] property, getter and setter](/img/f7/a3b79e3f7c4396a240eb5749c450d3.png)
[Android kotlin] property, getter and setter

The most basic code interpretation of C language

Docker builds sonarqube, mysql5.7 environment

Jenkins uses sonarqube to build pipeline code review project

EFCore高级Saas系统下单DbContext如何支持不同数据库的迁移
随机推荐
GBase 8c 模式可见性查询函数(一)
Résumé du websocket minier
数据模型设计方法概述
《天幕红尘》笔记与思考(六)因缺而需
Gbase 8C access authority query function (6)
Multi data source configuration of mongodb
[translation] Introduction to go RPC: Hello World
PayPal subscription process and API request
How to open a low commission account? Is it safe?
Summarize the plan, clarify the direction, concentrate and start a new situation -- the Counterpart Assistance Project of hexu software has achieved remarkable results
GBase 8c模式可见性查询函数(二)
Implementation of singleton mode in C #
Take a nap at home today
Try new methods
书写SQL必养成的好习惯
Docker pulls the redis image and runs it
Inode, soft link, hard link
Redis 主从、哨兵、集群架构有缺点比较
数据标准详细概述-2022
GBase 8c 字符串操作符