钉钉报警接入代码

@Service@Slf4jpublic class DingTalkUtil { @Value("${dingTalk.robot.url}") private String robotUrl; @Value("${dingTalk.robot.me}") private String me; // 钉钉密钥 @Value("${dingTalk.robot.secret}") private String secret; @Value("${dingTalk.enabled}") private Boolean enabled; private OkHttpClient okHttpClient; private static final ObjectMapper objectMapper = new ObjectMapper(); private static final MediaType jsonMediaType = MediaType.parse("application/json"); @PostConstruct public void init() { ExecutorService executorService = new ThreadPoolExecutor( 1, 5, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(100), ThreadFactoryBuilder.create().setNamePrefix("dingTalk-").build(), new ThreadPoolExecutor.CallerRunsPolicy() ); Dispatcher dispatcher = new Dispatcher(executorService); dispatcher.setMaxRequests(5); dispatcher.setMaxRequestsPerHost(5); okHttpClient = new OkHttpClient.Builder() .readTimeout(Duration.ofSeconds(1)) .connectTimeout(Duration.ofSeconds(1)) .callTimeout(Duration.ofSeconds(1)) .writeTimeout(Duration.ofSeconds(1)) .dispatcher(dispatcher) .build(); } /** * 异步发送钉钉机器人文本消息. */ public void sendTextMessage(String content) { doSendTextMessage(content, textMessage -> { }); } /** * 异步发送文本消息并@自己. */ public void sendTextMessageWithAtMe(String content) { doSendTextMessage(content, textMessage -> textMessage.getAt().getAtMobiles().add(me)); } /** * 异步发送文本消息并@所有人. */ public void sendTextMessageWithAtAll(String content) { doSendTextMessage(content, textMessage -> textMessage.getAt().setAtAll(true)); } private void doSendTextMessage(String content, Consumer<TextMessage> messageConfigurator) { if (!enabled) { return; } if (StringUtils.isBlank(content)) { throw new IllegalArgumentException("文本消息内容不能为空"); } TextMessage textMessage = new TextMessage(); textMessage.setText(new TextMessage.Content(content)); messageConfigurator.accept(textMessage); long timestamp = System.currentTimeMillis(); String sign = sign(timestamp); try { Request request = new Request.Builder() .url((robotUrl + "×tamp=" + timestamp + "&sign=" + sign)) .post(RequestBody.create(objectMapper.writeValueAsString(textMessage), jsonMediaType)) .build(); Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { log.error("发送钉钉消息失败, 请求: {}.", call, e); } @Override public void onResponse(@NotNull Call call, @NotNull Response response) { ResponseBody responseBody = response.body(); log.debug("钉钉发送成功, call: {}, resp: {}.", call.request().body(), responseBody); if (responseBody != null) responseBody.close(); } }); } catch (JsonProcessingException e) { throw ExceptionUtil.wrapRuntime(e); } } private String sign(long timestamp) { final String seed = (timestamp + "\n" + secret); try { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); byte[] result = mac.doFinal(seed.getBytes(StandardCharsets.UTF_8)); return URLEncoder.encode(Base64.getEncoder().encodeToString(result), StandardCharsets.UTF_8.displayName()); } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) { throw ExceptionUtil.wrapRuntime(e); } } @Getter private static class TextMessage { private final String msgtype = "text"; @Setter private Content text; private final At at = new At(); @Data @AllArgsConstructor private static class Content { private String content; } private static class At { @Setter private boolean isAtAll = false; @Getter private final List<String> atMobiles = new LinkedList<>(); // 不能删除,否则会导致生成的json字段名是atAll, 导致@所有人不生效 public boolean getIsAtAll() { return isAtAll; } } }}

@Service@Slf4jpublic class DingTalkUtil {    @Value("${dingTalk.robot.url}")    private String robotUrl;    @Value("${dingTalk.robot.me}")    private String me;    // 钉钉密钥    @Value("${dingTalk.robot.secret}")    private String secret;    @Value("${dingTalk.enabled}")    private Boolean enabled;    private OkHttpClient okHttpClient;    private static final ObjectMapper objectMapper = new ObjectMapper();    private static final MediaType jsonMediaType = MediaType.parse("application/json");    @PostConstruct    public void init() {        ExecutorService executorService = new ThreadPoolExecutor(                1,                5,                1,                TimeUnit.MINUTES,                new ArrayBlockingQueue<>(100),                ThreadFactoryBuilder.create().setNamePrefix("dingTalk-").build(),                new ThreadPoolExecutor.CallerRunsPolicy()        );        Dispatcher dispatcher = new Dispatcher(executorService);        dispatcher.setMaxRequests(5);        dispatcher.setMaxRequestsPerHost(5);        okHttpClient = new OkHttpClient.Builder()                .readTimeout(Duration.ofSeconds(1))                .connectTimeout(Duration.ofSeconds(1))                .callTimeout(Duration.ofSeconds(1))                .writeTimeout(Duration.ofSeconds(1))                .dispatcher(dispatcher)                .build();    }    /**     * 异步发送钉钉机器人文本消息.     */    public void sendTextMessage(String content) {        doSendTextMessage(content, textMessage -> {        });    }    /**     * 异步发送文本消息并@自己.     */    public void sendTextMessageWithAtMe(String content) {        doSendTextMessage(content, textMessage -> textMessage.getAt().getAtMobiles().add(me));    }    /**     * 异步发送文本消息并@所有人.     */    public void sendTextMessageWithAtAll(String content) {        doSendTextMessage(content, textMessage -> textMessage.getAt().setAtAll(true));    }    private void doSendTextMessage(String content, Consumer<TextMessage> messageConfigurator) {        if (!enabled) {            return;        }        if (StringUtils.isBlank(content)) {            throw new IllegalArgumentException("文本消息内容不能为空");        }        TextMessage textMessage = new TextMessage();        textMessage.setText(new TextMessage.Content(content));        messageConfigurator.accept(textMessage);        long timestamp = System.currentTimeMillis();        String sign = sign(timestamp);        try {            Request request = new Request.Builder()                    .url((robotUrl + "×tamp=" + timestamp + "&sign=" + sign))                    .post(RequestBody.create(objectMapper.writeValueAsString(textMessage), jsonMediaType))                    .build();            Call call = okHttpClient.newCall(request);            call.enqueue(new Callback() {                @Override                public void onFailure(@NotNull Call call, @NotNull IOException e) {                    log.error("发送钉钉消息失败, 请求: {}.", call, e);                }                @Override                public void onResponse(@NotNull Call call, @NotNull Response response) {                    ResponseBody responseBody = response.body();                    log.debug("钉钉发送成功, call: {}, resp: {}.", call.request().body(), responseBody);                    if (responseBody != null) responseBody.close();                }            });        } catch (JsonProcessingException e) {            throw ExceptionUtil.wrapRuntime(e);        }    }    private String sign(long timestamp) {        final String seed = (timestamp + "\n" + secret);        try {            Mac mac = Mac.getInstance("HmacSHA256");            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));            byte[] result = mac.doFinal(seed.getBytes(StandardCharsets.UTF_8));            return URLEncoder.encode(Base64.getEncoder().encodeToString(result), StandardCharsets.UTF_8.displayName());        } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {            throw ExceptionUtil.wrapRuntime(e);        }    }    @Getter    private static class TextMessage {        private final String msgtype = "text";        @Setter        private Content text;        private final At at = new At();        @Data        @AllArgsConstructor        private static class Content {            private String content;        }        private static class At {            @Setter            private boolean isAtAll = false;            @Getter            private final List<String> atMobiles = new LinkedList<>();            // 不能删除,否则会导致生成的json字段名是atAll, 导致@所有人不生效            public boolean getIsAtAll() {                return isAtAll;            }        }    }}

内容来源网络,如有侵权,联系删除,本文地址:https://www.230890.com/zhan/100298.html

(0)

相关推荐

  • 女子意外怀孕后不顾反对生下双胞胎,医生看后断言:活不过18岁

    “2008年11月份,我发现自己意外怀孕,去医院检查竟然是双胞胎,孩子爸爸想等家里条件好一些再生。第一次做母亲,我很舍不得。不顾丈夫反对生下了他们,不想我的这个决定毁了两个孩子的一辈子,也毁了我们原本幸福的一个家。”徐国玉看着趴在炕上坐不起来的双胞胎儿子眼中含泪地说。

    生活 2021年9月28日
  • 孕妇去人民医院好?还是妇幼保健院好?,人民医院好还是妇幼好

    很多宝妈都纠结到底是去人民医院产检生娃还是妇幼医院产检生娃。

    生活 2021年11月18日
  • 云选母婴布书(皇儿母婴旗舰店布书)

    MY FIRST BOOK作为一种儿童读物类潮流新品 ,为新生代宝妈所喜爱。一说儿童读物,大家最先想到的就是各种儿童绘本,但是绘本只要一到宝宝手里,往往被搞得破破烂烂、一地狼藉,妈妈还要担心印刷书籍的油墨会不会对宝宝造成伤害。MY FIRST BOOK布书,撕不烂、咬不破、可水洗,就这样火爆起来。

    生活 2021年12月21日
  • 张仲景经典名方,张仲景方子

    小编导读

    生活 2021年11月14日
  • 100套大数据可视化模板,附下载地址和源码

    昨天给大家分享了74套大数据模板,有大概300多粉丝收藏,可见大家对这块还是有很大的需求量的,今天趁着周末时间,给大家去网上找了找,发现更给力的大屏模板,大概统计了一下,差不多是100套左右,希望能够帮助到大家,如果对大家有帮助,请多多转发与收藏。

    科技 2021年11月29日
  • 半导体etf十大重仓股,半导体芯片股票

    号称“国家队”的大基金二期,开始对半导体产业加速布局。继15亿元投资入股芯片设备龙头北方华创(002371)后,大基金二期又参与国内封测龙头企业华天科技(002185)的定增,投资11.3亿元,获配股数为1.03亿股。此外,大基金二期近期还投资了半导体清洗设备上市公司至纯科技(603690)的子公司至微科技。截至目前,大基金二期对外投资的项目包括中芯国际、中芯南方、中芯京城、睿力集成、紫光展锐、华润微、南大光电(300346)、中微公司、北方华创、华天科技等近20家公司。(券商中国)

    生活 2021年11月7日