Browse Source

增加钉钉通知。移除邮件通知。

xda 2 years ago
parent
commit
e23dc660e8

+ 5 - 4
src/main/java/com/xxl/job/admin/core/alarm/JobAlarmer.java

@@ -16,7 +16,7 @@ import java.util.Map;
 
 @Component
 public class JobAlarmer implements ApplicationContextAware, InitializingBean {
-    private static Logger logger = LoggerFactory.getLogger(JobAlarmer.class);
+    private static final Logger logger = LoggerFactory.getLogger(JobAlarmer.class);
 
     private ApplicationContext applicationContext;
     private List<JobAlarm> jobAlarmList;
@@ -29,8 +29,8 @@ public class JobAlarmer implements ApplicationContextAware, InitializingBean {
     @Override
     public void afterPropertiesSet() throws Exception {
         Map<String, JobAlarm> serviceBeanMap = applicationContext.getBeansOfType(JobAlarm.class);
-        if (serviceBeanMap != null && serviceBeanMap.size() > 0) {
-            jobAlarmList = new ArrayList<JobAlarm>(serviceBeanMap.values());
+        if (serviceBeanMap.size() > 0) {
+            jobAlarmList = new ArrayList<>(serviceBeanMap.values());
         }
     }
 
@@ -45,7 +45,8 @@ public class JobAlarmer implements ApplicationContextAware, InitializingBean {
 
         boolean result = false;
         if (jobAlarmList!=null && jobAlarmList.size()>0) {
-            result = true;  // success means all-success
+            // success means all-success
+            result = true;
             for (JobAlarm alarm: jobAlarmList) {
                 boolean resultItem = false;
                 try {

+ 78 - 0
src/main/java/com/xxl/job/admin/core/alarm/impl/DingJobAlarm.java

@@ -0,0 +1,78 @@
+package com.xxl.job.admin.core.alarm.impl;
+
+import com.xxl.job.admin.core.alarm.JobAlarm;
+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.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+import org.springframework.web.client.RestTemplate;
+
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @Description: DingJobAlarm
+ * @Author: xda
+ * @Date: 2022/7/14 17:08
+ */
+@Component
+public class DingJobAlarm implements JobAlarm {
+
+    public static final Logger LOGGER = LoggerFactory.getLogger(DingJobAlarm.class);
+
+    public static final String BASE_URL = "https://oapi.dingtalk.com/robot/send?access_token=";
+
+    @Autowired
+    private RestTemplate restTemplate;
+
+    @Value("${work_env:}")
+    private String workEnv;
+
+    @Value("${dingAccessToken}")
+    private String dingAccessToken;
+
+    @Override
+    public boolean doAlarm(XxlJobInfo info, XxlJobLog jobLog) {
+        boolean alarmResult = true;
+        // send monitor email
+        if (info != null) {
+            Map<String, Object> map = loadEmailJobAlarmTemplate(info, jobLog, workEnv);
+            // 发送钉钉消息
+            try {
+                restTemplate.postForEntity(BASE_URL + dingAccessToken, map, Object.class);
+            } catch (Exception e) {
+                LOGGER.error(">>>>>>>>>>> xxl-job, job fail alarm email send error, JobLogId:{}", jobLog.getId(), e);
+                alarmResult = false;
+            }
+        }
+        return alarmResult;
+    }
+
+    private static Map<String, Object> loadEmailJobAlarmTemplate(XxlJobInfo info, XxlJobLog jobLog, String workEnv) {
+        HashMap<String, Object> map = new HashMap<>(2);
+        map.put("msgtype", "text");
+        String content =
+                "【告警信息】 \t\n" +
+                        "环境 : \t" + workEnv + "\t\n" +
+                        "负责人 : \t" + info.getAuthor() + "\t\n" +
+                        "任务id : \t" + info.getId() + "\t\n" +
+                        "任务名称 : \t" + info.getJobDesc() + "\t\n" +
+                        "执行器名称 : \t" + info.getExecutorHandler() + "\t\n" +
+                        "执行器ip : \t" + jobLog.getExecutorAddress() + "\t\n" +
+                        "任务参数 : \t" + jobLog.getExecutorParam() + "\t\n" +
+                        "LogId : \t" + jobLog.getId() + "\t\n" +
+                        "TriggerMsg : \t" + jobLog.getTriggerMsg().replace("<br>", "\n") + "\t\n" +
+                        "HandleCode : \t" + jobLog.getHandleMsg() + "\t\n" +
+                        "报警时间 : \t" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + "\t\n";
+        HashMap<String, String> cmap = new HashMap<>(1);
+        cmap.put("content", content);
+        map.put("text", cmap);
+        // 设置指定人
+        return map;
+    }
+}

+ 118 - 118
src/main/java/com/xxl/job/admin/core/alarm/impl/EmailJobAlarm.java

@@ -1,118 +1,118 @@
-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.nio.charset.StandardCharsets;
-import java.text.MessageFormat;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * job alarm by email
- *
- * @author xuxueli 2020-01-19
- */
-@Component
-public class EmailJobAlarm implements JobAlarm {
-    private static Logger logger = LoggerFactory.getLogger(EmailJobAlarm.class);
-
-    /**
-     * fail alarm
-     *
-     * @param jobLog
-     */
-    public boolean doAlarm(XxlJobInfo info, XxlJobLog jobLog){
-        boolean alarmResult = true;
-
-        // send monitor email
-        if (info!=null && info.getAlarmEmail()!=null && info.getAlarmEmail().trim().length()>0) {
-
-            // alarmContent
-            String alarmContent = "Alarm Job LogId=" + jobLog.getId();
-            if (jobLog.getTriggerCode() != ReturnT.SUCCESS_CODE) {
-                alarmContent += "<br>TriggerMsg=<br>" + jobLog.getTriggerMsg();
-            }
-            if (jobLog.getHandleCode()>0 && jobLog.getHandleCode() != ReturnT.SUCCESS_CODE) {
-                alarmContent += "<br>HandleCode=" + jobLog.getHandleMsg();
-            }
-
-            // email info
-            XxlJobGroup group = XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao().load(Integer.valueOf(info.getJobGroup()));
-            String personal = I18nUtil.getString("admin_name_full");
-            String title = I18nUtil.getString("jobconf_monitor");
-            String content = MessageFormat.format(loadEmailJobAlarmTemplate(),
-                    group!=null?group.getTitle():"null",
-                    info.getId(),
-                    info.getJobDesc(),
-                    alarmContent);
-
-            Set<String> emailSet = new HashSet<String>(Arrays.asList(info.getAlarmEmail().split(",")));
-            for (String email: emailSet) {
-
-                // make mail
-                try {
-                    MimeMessage mimeMessage = XxlJobAdminConfig.getAdminConfig().getMailSender().createMimeMessage();
-
-                    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, StandardCharsets.UTF_8.name());
-                    helper.setFrom(XxlJobAdminConfig.getAdminConfig().getEmailFrom(), personal);
-                    helper.setTo(email);
-                    helper.setSubject(title);
-                    helper.setText(content, true);
-
-                    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 alarmResult;
-    }
-
-    /**
-     * load email job alarm 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;
-    }
-
-}
+//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.nio.charset.StandardCharsets;
+//import java.text.MessageFormat;
+//import java.util.Arrays;
+//import java.util.HashSet;
+//import java.util.Set;
+//
+///**
+// * job alarm by email
+// *
+// * @author xuxueli 2020-01-19
+// */
+//@Component
+//public class EmailJobAlarm implements JobAlarm {
+//    private static Logger logger = LoggerFactory.getLogger(EmailJobAlarm.class);
+//
+//    /**
+//     * fail alarm
+//     *
+//     * @param jobLog
+//     */
+//    public boolean doAlarm(XxlJobInfo info, XxlJobLog jobLog){
+//        boolean alarmResult = true;
+//
+//        // send monitor email
+//        if (info!=null && info.getAlarmEmail()!=null && info.getAlarmEmail().trim().length()>0) {
+//
+//            // alarmContent
+//            String alarmContent = "Alarm Job LogId=" + jobLog.getId();
+//            if (jobLog.getTriggerCode() != ReturnT.SUCCESS_CODE) {
+//                alarmContent += "<br>TriggerMsg=<br>" + jobLog.getTriggerMsg();
+//            }
+//            if (jobLog.getHandleCode()>0 && jobLog.getHandleCode() != ReturnT.SUCCESS_CODE) {
+//                alarmContent += "<br>HandleCode=" + jobLog.getHandleMsg();
+//            }
+//
+//            // email info
+//            XxlJobGroup group = XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao().load(Integer.valueOf(info.getJobGroup()));
+//            String personal = I18nUtil.getString("admin_name_full");
+//            String title = I18nUtil.getString("jobconf_monitor");
+//            String content = MessageFormat.format(loadEmailJobAlarmTemplate(),
+//                    group!=null?group.getTitle():"null",
+//                    info.getId(),
+//                    info.getJobDesc(),
+//                    alarmContent);
+//
+//            Set<String> emailSet = new HashSet<String>(Arrays.asList(info.getAlarmEmail().split(",")));
+//            for (String email: emailSet) {
+//
+//                // make mail
+//                try {
+//                    MimeMessage mimeMessage = XxlJobAdminConfig.getAdminConfig().getMailSender().createMimeMessage();
+//
+//                    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, StandardCharsets.UTF_8.name());
+//                    helper.setFrom(XxlJobAdminConfig.getAdminConfig().getEmailFrom(), personal);
+//                    helper.setTo(email);
+//                    helper.setSubject(title);
+//                    helper.setText(content, true);
+//
+//                    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 alarmResult;
+//    }
+//
+//    /**
+//     * load email job alarm 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;
+//    }
+//
+//}

+ 20 - 0
src/main/java/com/xxl/job/admin/core/conf/BeanConfig.java

@@ -0,0 +1,20 @@
+package com.xxl.job.admin.core.conf;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.client.RestTemplate;
+
+/**
+ * @Description: BeanConfig
+ * @Author: xda
+ * @Date: 2022/7/14 17:13
+ */
+@Configuration
+public class BeanConfig {
+
+
+    @Bean
+    public RestTemplate restTemplate() {
+        return new RestTemplate();
+    }
+}

+ 3 - 2
src/main/java/com/xxl/job/admin/core/thread/JobFailMonitorHelper.java

@@ -18,7 +18,7 @@ import java.util.concurrent.TimeUnit;
  */
 public class JobFailMonitorHelper {
 	private static Logger logger = LoggerFactory.getLogger(JobFailMonitorHelper.class);
-	
+
 	private static JobFailMonitorHelper instance = new JobFailMonitorHelper();
 	public static JobFailMonitorHelper getInstance(){
 		return instance;
@@ -60,7 +60,8 @@ public class JobFailMonitorHelper {
 
 								// 2、fail alarm monitor
 								int newAlarmStatus = 0;		// 告警状态:0-默认、-1=锁定状态、1-无需告警、2-告警成功、3-告警失败
-								if (info!=null && info.getAlarmEmail()!=null && info.getAlarmEmail().trim().length()>0) {
+								if (info!=null) {
+								//if (info!=null && info.getAlarmEmail()!=null && info.getAlarmEmail().trim().length()>0) {
 									boolean alarmResult = XxlJobAdminConfig.getAdminConfig().getJobAlarmer().alarm(info, log);
 									newAlarmStatus = alarmResult?2:3;
 								} else {

+ 4 - 1
src/main/java/com/xxl/job/admin/core/trigger/XxlJobTrigger.java

@@ -181,8 +181,11 @@ public class XxlJobTrigger {
         triggerMsgSb.append("<br>").append(I18nUtil.getString("jobinfo_field_timeout")).append(":").append(jobInfo.getExecutorTimeout());
         triggerMsgSb.append("<br>").append(I18nUtil.getString("jobinfo_field_executorFailRetryCount")).append(":").append(finalFailRetryCount);
 
-        triggerMsgSb.append("<br><br><span style=\"color:#00c0ef;\" > >>>>>>>>>>>"+ I18nUtil.getString("jobconf_trigger_run") +"<<<<<<<<<<< </span><br>")
+
+        triggerMsgSb.append(I18nUtil.getString("jobconf_trigger_run"))
                 .append((routeAddressResult!=null&&routeAddressResult.getMsg()!=null)?routeAddressResult.getMsg()+"<br><br>":"").append(triggerResult.getMsg()!=null?triggerResult.getMsg():"");
+        //triggerMsgSb.append("<br><br><span style=\"color:#00c0ef;\" > >>>>>>>>>>>"+ I18nUtil.getString("jobconf_trigger_run") +"<<<<<<<<<<< </span><br>")
+        //        .append((routeAddressResult!=null&&routeAddressResult.getMsg()!=null)?routeAddressResult.getMsg()+"<br><br>":"").append(triggerResult.getMsg()!=null?triggerResult.getMsg():"");
 
         // 6、save log trigger-info
         jobLog.setExecutorAddress(address);