手把手封装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.yml或application.properties中添加钉钉配置:
dingtalk:platformOperateUrl:https://oapi.dingtalk.com/robot/send?access_token=你的token3. 核心功能解析
@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(){// 处理消息队列}}总结
通过这个实战案例,我们学习了如何:
- 优雅地封装第三方API调用
- 使用Spring注解简化开发
- 实现异步处理提升性能
- 合理设计工具类结构
- 考虑扩展性和可维护性
这个钉钉消息工具类不仅功能完善,而且易于扩展。你可以根据实际需求添加更多的消息类型支持,比如链接消息、卡片消息等。
希望这篇文章对你有所帮助,如果有任何问题,欢迎在评论区留言讨论!
更多精彩内容,请关注我的CSDN博客!