news 2026/8/21 5:48:16

手把手封装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/8/21 13:22:58

VSCode下Q#项目文档难产?这3个工具让你效率飙升300%

第一章&#xff1a;VSCode下Q#文档生成的现状与挑战在量子计算快速发展的背景下&#xff0c;Q# 作为微软推出的专用量子编程语言&#xff0c;其开发环境和工具链的完善程度直接影响开发者体验。Visual Studio Code&#xff08;VSCode&#xff09;作为主流编辑器之一&#xff0c…

作者头像 李华
网站建设 2026/8/21 21:30:05

Agent服务日志异常怎么办,资深架构师教你4步快速定位故障

第一章&#xff1a;Agent服务日志异常的常见现象与影响Agent服务作为系统监控、数据采集和自动化运维的核心组件&#xff0c;其日志记录的完整性与准确性至关重要。当日志出现异常时&#xff0c;往往会导致故障排查困难、监控失效甚至业务中断。常见的日志异常现象包括日志缺失…

作者头像 李华
网站建设 2026/8/21 22:15:04

阅读APP书源配置终极指南:三步快速搭建个人图书馆

阅读APP书源配置终极指南&#xff1a;三步快速搭建个人图书馆 【免费下载链接】Yuedu &#x1f4da;「阅读」APP 精品书源&#xff08;网络小说&#xff09; 项目地址: https://gitcode.com/gh_mirrors/yu/Yuedu 想要在阅读APP中畅享海量小说资源&#xff1f;掌握书源配…

作者头像 李华
网站建设 2026/8/20 18:28:01

全面解析运维工单管理在ITSM中的应用与价值

随着企业数字化转型的深入推进&#xff0c;IT系统的复杂性和业务依赖程度不断提高。传统人工管理的运维模式已经难以满足快速响应和高效协作的需求。运维工单管理应运而生&#xff0c;成为企业实现智能化、规范化运维管理的重要工具。不仅能够优化工单处理流程&#xff0c;还能…

作者头像 李华
网站建设 2026/8/20 21:39:19

PivotTable.js:三步完成专业级数据透视分析

在数据驱动的时代&#xff0c;如何快速从海量数据中提取有价值的信息成为每个团队面临的挑战。传统的数据分析工具往往需要复杂的配置和编程知识&#xff0c;而PivotTable.js通过创新的拖放界面设计&#xff0c;让数据分析变得像搭积木一样简单。 【免费下载链接】pivottable O…

作者头像 李华