Browse Source

添加钉钉机器人

许家凯 4 years ago
parent
commit
19677e636e

+ 14 - 0
pom.xml

@@ -11,9 +11,23 @@
 
     <properties>
         <java.version>1.8</java.version>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+        <maven.compiler.source>1.8</maven.compiler.source>
+        <maven.compiler.target>1.8</maven.compiler.target>
     </properties>
 
     <dependencies>
+
+        <dependency>
+            <groupId>com.squareup.okhttp3</groupId>
+            <artifactId>okhttp</artifactId>
+            <version>3.10.0</version>
+        </dependency>
+        <dependency>
+            <groupId>com.squareup.okhttp3</groupId>
+            <artifactId>logging-interceptor</artifactId>
+            <version>3.10.0</version>
+        </dependency>
         <dependency>
             <groupId>cn.hutool</groupId>
             <artifactId>hutool-all</artifactId>

+ 19 - 0
src/main/java/com/winhc/dataworks/flow/touch/TestDing.java

@@ -0,0 +1,19 @@
+package com.winhc.dataworks.flow.touch;
+
+import com.helospark.lightdi.LightDi;
+import com.helospark.lightdi.LightDiContext;
+import com.winhc.dataworks.flow.touch.utils.DingUtils;
+
+/**
+ * @Author: XuJiakai
+ * @Date: 2020/6/28 15:02
+ * @Description:
+ */
+public class TestDing {
+    public static void main(String[] args) {
+        LightDiContext context = LightDi.initContextByPackage(Main.class.getPackage().getName());
+        DingUtils bean = context.getBean(DingUtils.class);
+        boolean 测试 = bean.send("测试");
+        System.out.println(测试);
+    }
+}

+ 84 - 0
src/main/java/com/winhc/dataworks/flow/touch/configuration/OkHttpConfiguration.java

@@ -0,0 +1,84 @@
+package com.winhc.dataworks.flow.touch.configuration;
+
+import com.helospark.lightdi.annotation.Bean;
+import com.helospark.lightdi.annotation.Configuration;
+import lombok.extern.slf4j.Slf4j;
+import okhttp3.ConnectionPool;
+import okhttp3.OkHttpClient;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @Author: XuJiakai
+ * @Date: 2020/6/28 14:37
+ * @Description:
+ */
+@Slf4j
+@Configuration
+public class OkHttpConfiguration {
+
+    @Bean
+    public X509TrustManager x509TrustManager() {
+        return new X509TrustManager() {
+            @Override
+            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
+            }
+
+            @Override
+            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
+            }
+
+            @Override
+            public X509Certificate[] getAcceptedIssuers() {
+                return new X509Certificate[0];
+            }
+        };
+    }
+
+    @Bean
+    public SSLSocketFactory sslSocketFactory() {
+        try {
+            //信任任何链接
+            SSLContext sslContext = SSLContext.getInstance("TLS");
+            sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
+            return sslContext.getSocketFactory();
+        } catch (NoSuchAlgorithmException e) {
+            e.printStackTrace();
+        } catch (KeyManagementException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    /**
+     * Create a new connection pool with tuning parameters appropriate for a single-user application.
+     * The tuning parameters in this pool are subject to change in future OkHttp releases. Currently
+     */
+    @Bean
+    public ConnectionPool pool() {
+        return new ConnectionPool(200, 5, TimeUnit.MINUTES);
+    }
+
+    @Bean
+    public OkHttpClient okHttpClient() {
+        return new OkHttpClient.Builder()
+                .sslSocketFactory(sslSocketFactory(), x509TrustManager())
+                .addInterceptor(new OkHttpRetryInterceptor(3))
+                //是否开启缓存
+                .retryOnConnectionFailure(false)
+                .connectionPool(pool())
+                .connectTimeout(10L, TimeUnit.SECONDS)
+                .readTimeout(10L, TimeUnit.SECONDS)
+                .build();
+    }
+
+}

+ 48 - 0
src/main/java/com/winhc/dataworks/flow/touch/configuration/OkHttpRetryInterceptor.java

@@ -0,0 +1,48 @@
+package com.winhc.dataworks.flow.touch.configuration;
+
+import lombok.extern.slf4j.Slf4j;
+import okhttp3.Interceptor;
+import okhttp3.Request;
+import okhttp3.Response;
+
+import java.io.IOException;
+
+/**
+ * @Author: XuJiakai
+ * @Date: 2020/6/28 14:38
+ * @Description:
+ */
+@Slf4j
+public class OkHttpRetryInterceptor implements Interceptor {
+    //最大重试次数
+    public int maxRetry;
+    //假如设置为3次重试的话,则最大可能请求4次(默认1次+3次重试)
+
+    public OkHttpRetryInterceptor(int maxRetry) {
+        this.maxRetry = maxRetry;
+    }
+
+    @Override
+    public Response intercept(Chain chain) throws IOException {
+        Request request = chain.request();
+        int retryNum = 0;
+        while (true) {
+            try {
+                Response response = chain.proceed(request);
+                while (!response.isSuccessful() && retryNum < maxRetry) {
+                    retryNum++;
+                    log.error("response code : {} ok http retry:{} request url: {} ,response body:{}", response.code(), retryNum, request.url(), response.body().string());
+                    response.close();
+                    response = chain.proceed(request);
+                }
+                return response;
+            } catch (Exception e) {
+                log.error(e.getMessage(), e);
+                log.error("ok http retry:{} request url: {} ", retryNum, request.url());
+                if (retryNum++ > maxRetry) {
+                    throw e;
+                }
+            }
+        }
+    }
+}

+ 88 - 0
src/main/java/com/winhc/dataworks/flow/touch/utils/DingUtils.java

@@ -0,0 +1,88 @@
+package com.winhc.dataworks.flow.touch.utils;
+
+import cn.hutool.crypto.digest.HMac;
+import cn.hutool.crypto.digest.HmacAlgorithm;
+import com.helospark.lightdi.annotation.Autowired;
+import com.helospark.lightdi.annotation.Component;
+import com.helospark.lightdi.annotation.Value;
+import com.winhc.dataworks.flow.touch.bean.Entry;
+import lombok.SneakyThrows;
+import lombok.extern.slf4j.Slf4j;
+import okhttp3.*;
+import org.apache.commons.codec.binary.Base64;
+
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.util.Objects;
+
+/**
+ * @Author: XuJiakai
+ * @Date: 2020/6/28 14:39
+ * @Description:
+ */
+@Slf4j
+@Component
+public class DingUtils {
+    @Autowired
+    private OkHttpClient client;
+    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
+    private static final String URL = "https://oapi.dingtalk.com/robot/send?access_token=2773b742b74d84599c4f05f7b42cacd6714b10c33cd4c74402649019fa7e56c8";
+    @Value("${ding-secret}")
+    private String dingSecret;
+
+
+    public boolean send(String msg) {
+        Entry<Long, String> sign = getSign();
+        String query = "&timestamp=" + sign.getKey() + "&sign=" + sign.getValue();
+        try {
+            String post = post(URL + query, getPostBody(msg));
+            log.info(post);
+            return post.contains("ok");
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+            return false;
+        }
+    }
+
+
+    private String post(String url, String json) throws IOException {
+        RequestBody body = RequestBody.create(JSON, json);
+        try (Response response = client.newCall((new Request.Builder()).url(url).post(body).build()).execute()) {
+            return parseBody(response);
+        } catch (Exception e) {
+            e.printStackTrace();
+            return "";
+        }
+    }
+
+    private String get(String url) throws IOException {
+        try (Response response = client.newCall(new Request.Builder().url(url).get().build()).execute()) {
+            return parseBody(response);
+        }
+    }
+
+    private static String parseBody(Response response) throws IOException {
+        return response == null ? "" : response.isSuccessful() ? Objects.requireNonNull(response.body()).string() : "";
+    }
+
+    private static String getPostBody(String msg) {
+        return "{\"msgtype\": \"text\",\"text\": {\"content\": \"" + msg + "\"}}";
+    }
+
+    @SneakyThrows
+    private Entry<Long, String> getSign() {
+        Long timestamp = System.currentTimeMillis();
+        String stringToSign = timestamp + "\n" + dingSecret;
+
+
+        byte[] key = dingSecret.getBytes("UTF-8");
+        HMac mac = new HMac(HmacAlgorithm.HmacSHA256, key);
+        byte[] signData = mac.digest(stringToSign);
+
+        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
+        Entry<Long, String> entry = new Entry<>();
+        entry.setKey(timestamp);
+        entry.setValue(sign);
+        return entry;
+    }
+}

+ 2 - 1
src/main/resources/dataworks-config.properties

@@ -1,3 +1,4 @@
 access-key-id:LTAI4G4n7pAW8tUbJVkkZQPD
 access-key-secret:uNJOBskzcDqHq1TYG3m2rebR4c1009
-region-id:cn-shanghai
+region-id:cn-shanghai
+ding-secret:SECe7b26876f443e77f872b8b10880e39b3c5dfaf44855f1aa3235372bb73698ab6