钉钉报警接入代码

@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)

相关推荐

  • 产妇产前125斤,产后112斤,多亏婆婆做的花式月子餐。

    今天是欣欣坐月子的第28天,还有两天就满月啦, 婆婆本来想让她做满42天的,但欣欣自己觉得30天差不多了,传统月子都是坐满30天,她婆婆也就同意了,毕竟平常 不生活在一起,只有过年回家待一段时间团聚。 即便如此,欣欣还是很感谢婆婆,每天不辞辛苦地买菜、做饭,给她和宝宝洗衣服。每次都主动问她想吃什么,做得清淡又好吃。欣欣产前125斤,生完第三天112斤,月子都快做完了, 体重还是维持在112斤左右,没胖也没瘦,打算出了月子后面再慢慢减吧,争取再瘦7斤,回到孕前体重,得益于她婆婆做的花样月子餐,发上来给大家看看,给即将坐月子的产妈们一个参考,也许有你爱吃的哟~

    生活 2021年12月25日
  • 为什么有些人喜欢以艺术的名义变丑?

    近日(2021年11月12日),奢侈品牌迪奥,因在上海的《迪奥与艺术》展览中展出了一张风格诡异的照片(被网友批评“丑化亚裔形象”),被骂上了热搜。事实上,近年来此类事件已是屡见不鲜、数不胜数,如6月份的清华美院模特事件,以及2018年DG杜嘉班纳的辱华广告等等。很显然,对于相应的机构、相关的艺术家心里想必非常清楚,其此类作品的发布出来一定会引起舆论界的一片批评之声,但他们为什么还趋之若鹜、乐此不疲呢?当然,他们都会以艺术之名找到一个冠冕堂皇的理由——审美差异。我想说,这些都是无稽之谈,根本的原因还在于利益,在于对中国巨大艺术市场的谋夺。

    生活 2021年11月20日
  • 币圈招财猫:11/4日区块链早讯

    1. 板球NFT平台Faze Technologies完成1740万美元种子轮融资,Tiger Global领投; 2. 加密指数基金管理公司Bitwise宣布推出Bitwise ...

    科技 2021年11月4日
  • 周将迎来其第四次IPO,但“赶上了晚一集”?

    文丨BT财经 Han 在二级市场,中国互联网公司最近几个月有点“受挫”。腾讯阿里的市值缩水并没有少,而Aauto faster的跌幅更大,更不用说低迷的互联网教育培训板块了。 穿红...

    科技 2021年10月27日
  • 监管层“违法”!跨境互联网经纪行业波动较大,或影响1600万用户。

    近日,央行官员的相关表态,让跨境互联网券商行业弥漫着一种紧张的气氛。

    生活 2021年10月30日