luxueshi 3 years ago
commit
cc70a63a6a

+ 46 - 0
pom.xml

@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+
+    <groupId>com.persagy</groupId>
+    <artifactId>sdk-minitor</artifactId>
+    <version>1.0-RELEASE</version>
+
+    <properties>
+        <maven.compiler.source>8</maven.compiler.source>
+        <maven.compiler.target>8</maven.compiler.target>
+    </properties>
+
+    <dependencies>
+        <!--糊涂工具-->
+        <dependency>
+            <groupId>cn.hutool</groupId>
+            <artifactId>hutool-all</artifactId>
+            <version>4.0.12</version>
+        </dependency>
+        <dependency>
+            <groupId>cn.hutool</groupId>
+            <artifactId>hutool-all</artifactId>
+            <version>4.0.12</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.directory.studio</groupId>
+            <artifactId>org.apache.commons.codec</artifactId>
+            <version>1.8</version>
+        </dependency>
+        <dependency>
+            <groupId>log4j</groupId>
+            <artifactId>log4j</artifactId>
+            <version>1.2.17</version>
+        </dependency>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <version>4.12</version>
+            <scope>test</scope>
+        </dependency>
+    </dependencies>
+
+</project>

+ 76 - 0
src/main/java/AlarmUtil.java

@@ -0,0 +1,76 @@
+import cn.hutool.http.HttpUtil;
+import cn.hutool.json.JSONObject;
+import cn.hutool.json.JSONUtil;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.log4j.Logger;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import java.net.URLEncoder;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class AlarmUtil {
+
+    private final static Logger log = Logger.getLogger(AlarmUtil.class);
+
+    private static final String DING_DING_URL = "https://oapi.dingtalk.com/robot/send?access_token=fc68871c0fd75e3921f370a7f0b936fd78d879cf2e36c94a1dcb07994fc25202";
+
+    private static final String LOCAL_SECRET = "SECb3651d77a3baffb27e1c492c0df786262ce52aca6ba6cc15c83795f56ea9281f";
+
+    private static final String SHA = "HmacSHA256";
+
+    private static final String CHARSET_NAME = "UTF-8";
+
+    private static final String SUCCESS_CODE = "0";
+
+    public static boolean alarmByDingDing(String content, boolean isAtAll, List<String> mobileList) {
+        String wholeUrl = generateWholeUrl();
+        if (null == wholeUrl) {
+            return false;
+        }
+        String reqStr = buildReqStr(content, isAtAll, mobileList);
+        String result = HttpUtil.post(wholeUrl, reqStr);
+        JSONObject jsonObject = JSONUtil.parseObj(result);
+        if (null == jsonObject.get("errcode")) {
+            return false;
+        }
+        return String.valueOf(jsonObject.get("errcode")).equals(SUCCESS_CODE) ? true : false;
+    }
+
+    private static String generateWholeUrl() {
+        try {
+            Long timestamp = System.currentTimeMillis();
+            String stringToSign = timestamp + "\n" + LOCAL_SECRET;
+            Mac mac = Mac.getInstance(SHA);
+            mac.init(new SecretKeySpec(LOCAL_SECRET.getBytes(CHARSET_NAME), SHA));
+            byte[] signData = mac.doFinal(stringToSign.getBytes(CHARSET_NAME));
+            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), CHARSET_NAME);
+            return DING_DING_URL + "&timestamp=" + timestamp + "&sign=" + sign;
+        } catch (Exception e) {
+            log.error("生成钉钉请求全路径失败", e);
+            return null;
+        }
+    }
+
+    private static String buildReqStr(String content, boolean isAtAll, List<String> mobileList) {
+        //消息内容
+        Map<String, String> contentMap = new HashMap<>();
+        contentMap.put("content", content);
+
+        //通知人
+        Map<String, Object> atMap = new HashMap<>();
+        //是否通知所有人
+        atMap.put("isAtAll", isAtAll);
+        //通知具体人的手机号码列表
+        atMap.put("atMobiles", mobileList);
+
+        Map<String, Object> reqMap = new HashMap<>();
+        reqMap.put("msgtype", "text");
+        reqMap.put("text", contentMap);
+        reqMap.put("at", atMap);
+
+        return JSONUtil.toJsonStr(reqMap);
+    }
+}

+ 56 - 0
src/main/java/MinitorApplication.java

@@ -0,0 +1,56 @@
+import org.apache.log4j.Logger;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Timer;
+import java.util.TimerTask;
+
+public class MinitorApplication {
+
+    private final static Logger log = Logger.getLogger(MinitorApplication.class);
+
+    private static int errorTimes = 0;
+
+    private static int requestTimes = 0;
+
+    private static final String ALARM_CONTENT = "每分钟访问一次SDK接口,连续5分钟未获取到数据,请查看服务情况" + "\ud83c\udf4e";
+
+    private static final String MINITOR_ALARM_CONTENT = "定时监控程序运行异常";
+
+    private static final String ADMIN_PHONE = "18618105263";
+
+    public static void main(String[] args) {
+        TimerTask timerTask = new TimerTask() {
+            @Override
+            public void run() {
+                try {
+                    if (errorTimes == 5 && requestTimes == 5) {
+                        //钉钉群通知,报警
+                        boolean alarmResult = AlarmUtil.alarmByDingDing(ALARM_CONTENT, true, null);
+                        log.info("钉钉报警发送结果:" + alarmResult);
+                        errorTimes = 0;
+                        requestTimes = 0;
+                    } else {
+                        //访问SDK接口
+                        boolean sdkResult = RequestUtil.requestSDK();
+                        requestTimes++;
+
+                        if (!sdkResult) {
+                            //失败次数增加1
+                            errorTimes++;
+                        }
+                    }
+                } catch (Exception e) {
+                    List<String> mobileList = new ArrayList<>();
+                    mobileList.add(ADMIN_PHONE);
+                    AlarmUtil.alarmByDingDing(MINITOR_ALARM_CONTENT, false, mobileList);
+                    log.error("定时任务执行异常,", e);
+                }
+            }
+        };
+        // 计时器
+        Timer timer = new Timer();
+        // 添加执行任务(延迟 0s 执行,每 60s 执行一次)
+        timer.schedule(timerTask, 0, 5000);
+    }
+}

+ 21 - 0
src/main/java/RequestUtil.java

@@ -0,0 +1,21 @@
+import cn.hutool.http.HttpUtil;
+import cn.hutool.json.JSONUtil;
+import org.apache.log4j.Logger;
+
+public class RequestUtil {
+
+    private final static Logger log = Logger.getLogger(RequestUtil.class);
+    private static final String SDK_URL = "http://localhost:8808/post";
+    private static final String REQUEST_STR = "[\"基础对象\"]";
+
+    public static boolean requestSDK() {
+        try {
+            String result = HttpUtil.post(SDK_URL, REQUEST_STR);
+            log.debug("SDK接口返回:" + result);
+            return JSONUtil.isJson(result);
+        } catch (Exception e) {
+            log.error("SDK接口调用异常", e);
+            return false;
+        }
+    }
+}

+ 42 - 0
src/main/resources/log4j.properties

@@ -0,0 +1,42 @@
+#priority:debug<info<warn<error
+log4j.rootLogger=debug,stdout,info,debug,warn,error
+#console
+log4j.appender.stdout=org.apache.log4j.ConsoleAppender
+log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
+log4j.appender.stdout.layout.ConversionPattern=[%d{yyyy-MM-ddHH:mm:ssa}]:%p%l%m%n
+#info
+log4j.logger.info=info
+log4j.appender.info=org.apache.log4j.DailyRollingFileAppender
+log4j.appender.info.DatePattern='_'yyyy-MM-dd'.log'
+log4j.appender.info.File=E:/minitor-logs/info.log
+log4j.appender.info.Append=true
+log4j.appender.info.Threshold=INFO
+log4j.appender.info.layout=org.apache.log4j.PatternLayout
+log4j.appender.info.layout.ConversionPattern=%d{yyyy-MM-ddHH:mm:ssa}[Thread:%t][Class:%c>>Method:%l]%n%p:%m%n
+##debug
+#log4j.logger.debug=debug
+#log4j.appender.debug=org.apache.log4j.DailyRollingFileAppender
+#log4j.appender.debug.DatePattern='_'yyyy-MM-dd'.log'
+#log4j.appender.debug.File=E:/minitor-logs/debug.log
+#log4j.appender.debug.Append=true
+#log4j.appender.debug.Threshold=DEBUG
+#log4j.appender.debug.layout=org.apache.log4j.PatternLayout
+#log4j.appender.debug.layout.ConversionPattern=%d{yyyy-MM-ddHH:mm:ssa}[Thread:%t][Class:%c>>Method:%l]%n%p:%m%n
+##warn
+#log4j.logger.warn=warn
+#log4j.appender.warn=org.apache.log4j.DailyRollingFileAppender
+#log4j.appender.warn.DatePattern='_'yyyy-MM-dd'.log'
+#log4j.appender.warn.File=E:/minitor-logs/warn.log
+#log4j.appender.warn.Append=true
+#log4j.appender.warn.Threshold=WARN
+#log4j.appender.warn.layout=org.apache.log4j.PatternLayout
+#log4j.appender.warn.layout.ConversionPattern=%d{yyyy-MM-ddHH:mm:ssa}[Thread:%t][Class:%c>>Method:%l]%n%p:%m%n
+#error
+log4j.logger.error=error
+log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
+log4j.appender.error.DatePattern='_'yyyy-MM-dd'.log'
+log4j.appender.error.File=E:/minitor-logs/error.log
+log4j.appender.error.Append=true
+log4j.appender.error.Threshold=ERROR
+log4j.appender.error.layout=org.apache.log4j.PatternLayout
+log4j.appender.error.layout.ConversionPattern=%d{yyyy-MM-ddHH:mm:ssa}[Thread:%t][Class:%c>>Method:%l]%n%p:%m%n

+ 11 - 0
src/test/java/AlarmUtilTest.java

@@ -0,0 +1,11 @@
+import org.junit.Assert;
+import org.junit.Test;
+
+public class AlarmUtilTest {
+
+    @Test
+    public void alarmTest() {
+        boolean result = AlarmUtil.alarmByDingDing("钉钉发送通知,单元测试", true, null);
+        Assert.assertTrue(result);
+    }
+}