news 2026/4/15 19:43:23

手把手封装Utils - 钉钉消息工具类实战教程

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
手把手封装Utils - 钉钉消息工具类实战教程

手把手封装Utils - 钉钉消息工具类实战教程

前言

在日常开发中,我们经常需要集成各种第三方服务,比如钉钉消息推送。今天我们来手把手封装一个实用的钉钉消息工具类,让你的代码更加优雅和可维护。

完整代码展示

先上完整代码,一睹为快:

importcn.hutool.http.HttpRequest;importcn.hutool.json.JSONUtil;importlombok.extern.slf4j.Slf4j;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.scheduling.annotation.Async;importorg.springframework.stereotype.Component;importjava.util.HashMap;importjava.util.Map;/** * 钉钉消息工具 */@Slf4j@ComponentpublicclassDingTalkUtils{@Value("${dingtalk.platformOperateUrl}")privateStringplatfromOperateUrl;/** * 群里面发送消息 * @param title 消息标题 * @param content 消息内容 */@AsyncpublicvoidsendTextMsg(Stringtitle,Stringcontent){// 组装请求内容StringreqStr=buildReqTextStr(title,content);// 推送消息(http请求)Stringresult=HttpRequest.post(platfromOperateUrl).body(reqStr).execute().body();log.info("钉钉请求发送成功,返回结果:{}",result);}/** * 组装请求报文-text类型 * * @param content 消息内容 * @return */publicstaticStringbuildReqTextStr(Stringtitle,Stringcontent){Map<String,String>contentMap=newHashMap<>();content="【"+title+"】"+"\n"+content;contentMap.put("content",content);Map<String,Object>reqMap=newHashMap<>();reqMap.put("msgtype","text");reqMap.put("text",contentMap);returnJSONUtil.toJsonStr(reqMap);}publicstaticvoidmain(String[]args){DingTalkUtilsdingTalkUtils=newDingTalkUtils();dingTalkUtils.sendTextMsg("测试标题","测试内容");}}

详细解析

1. 依赖引入

首先,我们需要在pom.xml中引入相关依赖:

<!-- Hutool工具包 --><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.16</version></dependency><!-- Lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency>

2. 配置说明

application.ymlapplication.properties中添加钉钉配置:

dingtalk:platformOperateUrl:https://oapi.dingtalk.com/robot/send?access_token=你的token

3. 核心功能解析

@Slf4j注解

使用Lombok的@Slf4j注解,自动生成日志对象,简化日志记录代码。

@Component注解

将工具类注册为Spring组件,方便依赖注入。

@Async注解

实现异步消息发送,避免阻塞主线程,提升系统性能。

@Value注解

从配置文件中读取钉钉Webhook地址,实现配置与代码分离。

4. 方法详解

sendTextMsg方法
@AsyncpublicvoidsendTextMsg(Stringtitle,Stringcontent)
  • 功能:发送文本消息到钉钉群
  • 参数
    • title:消息标题,会被格式化为【标题】格式
    • content:消息内容
  • 特性:异步执行,不会阻塞调用线程
buildReqTextStr方法
publicstaticStringbuildReqTextStr(Stringtitle,Stringcontent)
  • 功能:构建钉钉文本消息的请求体
  • 返回值:JSON格式的请求字符串
  • 格式化:自动将标题和内容拼接成钉钉支持的格式

5. 使用示例

基本使用
@AutowiredprivateDingTalkUtilsdingTalkUtils;// 发送消息dingTalkUtils.sendTextMsg("系统告警","服务器CPU使用率超过90%");
在异常处理中使用
@ControllerAdvicepublicclassGlobalExceptionHandler{@AutowiredprivateDingTalkUtilsdingTalkUtils;@ExceptionHandler(Exception.class)publicvoidhandleException(Exceptione){log.error("系统异常",e);dingTalkUtils.sendTextMsg("系统异常",e.getMessage());}}

6. 扩展功能

支持Markdown消息
publicvoidsendMarkdownMsg(Stringtitle,Stringcontent){Map<String,String>markdownMap=newHashMap<>();markdownMap.put("title",title);markdownMap.put("text",content);Map<String,Object>reqMap=newHashMap<>();reqMap.put("msgtype","markdown");reqMap.put("markdown",markdownMap);StringreqStr=JSONUtil.toJsonStr(reqMap);Stringresult=HttpRequest.post(platfromOperateUrl).body(reqStr).execute().body();log.info("钉钉Markdown消息发送成功,返回结果:{}",result);}
支持@指定用户
publicvoidsendTextMsgAt(Stringtitle,Stringcontent,List<String>atMobiles){Map<String,Object>reqMap=buildReqTextMap(title,content);Map<String,Object>atMap=newHashMap<>();atMap.put("atMobiles",atMobiles);atMap.put("isAtAll",false);reqMap.put("at",atMap);StringreqStr=JSONUtil.toJsonStr(reqMap);Stringresult=HttpRequest.post(platfromOperateUrl).body(reqStr).execute().body();log.info("钉钉@消息发送成功,返回结果:{}",result);}

7. 最佳实践

1. 错误处理增强
@AsyncpublicvoidsendTextMsg(Stringtitle,Stringcontent){try{StringreqStr=buildReqTextStr(title,content);Stringresult=HttpRequest.post(platfromOperateUrl).body(reqStr).timeout(5000)// 设置超时时间.execute().body();log.info("钉钉消息发送成功,返回结果:{}",result);}catch(Exceptione){log.error("钉钉消息发送失败",e);// 可以在这里实现重试机制或降级处理}}
2. 消息队列解耦
@ServicepublicclassDingTalkService{@AutowiredprivateRedisTemplate<String,Object>redisTemplate;privatestaticfinalStringDINGTALK_QUEUE="dingtalk:queue";publicvoidsendMessageAsync(Stringtitle,Stringcontent){Map<String,String>message=newHashMap<>();message.put("title",title);message.put("content",content);redisTemplate.opsForList().rightPush(DINGTALK_QUEUE,message);}// 通过定时任务或消息监听器处理队列@Scheduled(fixedDelay=1000)publicvoidprocessMessageQueue(){// 处理消息队列}}

总结

通过这个实战案例,我们学习了如何:

  1. 优雅地封装第三方API调用
  2. 使用Spring注解简化开发
  3. 实现异步处理提升性能
  4. 合理设计工具类结构
  5. 考虑扩展性和可维护性

这个钉钉消息工具类不仅功能完善,而且易于扩展。你可以根据实际需求添加更多的消息类型支持,比如链接消息、卡片消息等。

希望这篇文章对你有所帮助,如果有任何问题,欢迎在评论区留言讨论!


更多精彩内容,请关注我的CSDN博客!

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/14 0:24:03

【独家披露】资深工程师私藏的VSCode Jupyter量子模拟参数清单

第一章&#xff1a;VSCode Jupyter量子模拟参数概述在现代量子计算开发中&#xff0c;VSCode 结合 Jupyter Notebook 插件为开发者提供了高效的交互式编程环境。通过集成 Python 与 Qiskit 等量子计算框架&#xff0c;用户可在本地或远程执行量子电路模拟&#xff0c;并实时查看…

作者头像 李华
网站建设 2026/4/12 9:20:02

如何快速打造专属量子开发环境?VSCode + Azure QDK扩展开发全攻略

第一章&#xff1a;量子开发环境搭建的背景与意义 随着量子计算从理论研究逐步迈向工程实现&#xff0c;开发者对可编程量子系统的访问需求日益增长。构建一个稳定、高效的量子开发环境&#xff0c;已成为探索量子算法、验证量子协议和推动应用落地的关键前提。传统计算环境无法…

作者头像 李华
网站建设 2026/4/15 12:04:36

AI语音合成推理优化终极指南:35倍性能提升的完整教程

AI语音合成推理优化终极指南&#xff1a;35倍性能提升的完整教程 【免费下载链接】GPT-SoVITS 项目地址: https://gitcode.com/GitHub_Trending/gp/GPT-SoVITS 在当今AI语音合成技术快速发展的时代&#xff0c;推理速度已成为影响用户体验的关键因素。本文将深入解析如…

作者头像 李华
网站建设 2026/4/15 12:02:37

跨语言阅读革命:kiss-translator智能翻译插件深度解析

跨语言阅读革命&#xff1a;kiss-translator智能翻译插件深度解析 【免费下载链接】kiss-translator A simple, open source bilingual translation extension & Greasemonkey script (一个简约、开源的 双语对照翻译扩展 & 油猴脚本) 项目地址: https://gitcode.com…

作者头像 李华
网站建设 2026/4/9 13:29:29

基于MATLAB实现的鲁棒性音频数字水印系统

基于 MATLAB 实现的 鲁棒性音频数字水印系统 &#xff0c;结合 DWT-DCT联合变换 和 量化索引调制&#xff08;QIM&#xff09;&#xff0c;支持二值水印嵌入与提取&#xff0c;并通过仿真实验验证其抗攻击能力。一、系统架构设计二、核心代码 1. 水印预处理&#xff08;二值化与…

作者头像 李华