【若依框架】定时任务调用异步服务,实现每天定时发送钉钉消息通知

编程入门 行业动态 更新时间:2024-10-17 11:24:35

【若依<a href=https://www.elefans.com/category/jswz/34/1770644.html style=框架】定时任务调用异步服务,实现每天定时发送钉钉消息通知"/>

【若依框架】定时任务调用异步服务,实现每天定时发送钉钉消息通知

文章目录

  • 后端实现思路
  • 实现步骤
    • 1. 添加依赖
    • 2. 配置DingTalkUtils工具类
    • 3. 设置定时任务
    • 4. 异步任务-发送钉钉消息
    • 5. 配置白名单
    • 代码

后端实现思路

1. 添加hutool\taobao-sdk 依赖
2. DingtalkUtils 工具类配置 agentID,appKey,appSecret
3. 定时任务① 每天早上8点查询出将到期列表 willExipreList② 把将到期列表传给 异步任务 GrmsAsynTaskService.sendMessageForEveryDay(传进来 将过期列表 willExipreList)异步任务里面处理:发送通知:massage.append(xxx批次,xxx货物,保质期到 xxx 截止,即将过期,请尽快优先处理)

实现步骤

1. 添加依赖

        <dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.3.10</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>taobao-sdk</artifactId><version>20200526</version></dependency>

2. 配置DingTalkUtils工具类

// 这三个需要配置 ,钉钉运维人员提供
private final  static  Long agentId= xxxxL;   
private final  static  String appkey= "xxxx";
private final  static  String appsecret= "xxxx";
package com.tn.grmsmon.utils;import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.util.ArrayUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;import java.util.Arrays;
import java.util.List;/*** @Description* @Author lpz* @Date 2020-08-05*/
public class DingtalkUtils {private static final Logger logger = LogManager.getLogger(DingtalkUtils.class);private final  static  Long agentId= xxxxL;   // 这三个需要配置private final  static  String appkey= "xxxx";private final  static  String appsecret= "xxxx";private final static TimedCache<String, String> CACHE = CacheUtil.newTimedCache(2 * 1000 * 60);private DingtalkUtils() {}/*** 发送钉钉机器人通知到GRMS运维群** @param title* @param message* @return* @throws Exception*/public static void sendMessageToGrmsOperations(String title, String message) {try {// 这个token怎么获取?String requestUrl = "=xxxx";DingTalkClient client = new DefaultDingTalkClient(requestUrl);OapiRobotSendRequest request = new OapiRobotSendRequest();String content = "GRMS: " + title + "\n" + message;request.setMsgtype("text");OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();text.setContent(content);request.setText(text);OapiRobotSendResponse response = client.execute(request);} catch (Exception e) {e.printStackTrace();}}/*** 发送钉钉通知消息** @param content 发送内容* @param phones  发送人手机号* @return 操作结果* @throws Exception 异常*/public static void sendMessage(String content, List<String> phones) throws Exception {
//        content=content+"时间戳"+System.currentTimeMillis();String requestUrl = "";DingTalkClient client = new DefaultDingTalkClient(requestUrl);OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();request.setUseridList(getUserIdByMobile(phones));   // todo:发送消息的时候,根据钉钉登陆手机号获取userId,发送到指定人,  所以本系统中需要配置用户电话号码,需要拿到钉钉登录的电话号码request.setAgentId(agentId);request.setToAllUser(false);OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();msg.setMsgtype("text");msg.setText(new OapiMessageCorpconversationAsyncsendV2Request.Text());msg.getText().setContent(content);request.setMsg(msg);OapiMessageCorpconversationAsyncsendV2Response response = client.execute(request, dingRequestGetToken(appkey, appsecret));logger.info("发送结果...."+response.getCode()+"#" + response.getMessage()+"#" +response.getErrorCode()+"#" +response.getErrmsg());}/*** 获取token** @return token* @throws Exception*/public static String dingRequestGetToken(String appKey, String appSecret) throws Exception {logger.debug("已经入获取token方法");String token = CACHE.get(appKey + "accessToken", false);  // token获取后不变化if (StringUtils.isNotBlank(token)) {logger.debug("从缓存中返回token");return token;}logger.debug("开始请求获取token");DingTalkClient client = new DefaultDingTalkClient("");OapiGettokenRequest req = new OapiGettokenRequest();req.setAppkey(appKey);req.setAppsecret(appSecret);req.setHttpMethod("GET");OapiGettokenResponse execute = client.execute(req);if (!"0".equals(execute.getErrorCode())) {logger.debug("token获取失败,错误信息为:{}", execute.getErrmsg());throw new IllegalArgumentException(execute.getErrmsg());}String accessToken = execute.getAccessToken();logger.debug("token获取成功:{}", accessToken);CACHE.put(appKey + "accessToken", accessToken);return accessToken;}/*** 根据钉钉登陆手机号获取userId** @param mobiles 手机号* @return userIds* @throws Exception 异常*/public static String getUserIdByMobile(List<String> mobiles) throws Exception {logger.debug("进入钉钉根据手机号码获取userId");String token = dingRequestGetToken(appkey,appsecret);logger.debug("已获取token为:{}", token);DingTalkClient client = new DefaultDingTalkClient("");OapiUserGetByMobileRequest request = new OapiUserGetByMobileRequest();String[] userIds = new String[mobiles.size()];int i = 0;while (i < mobiles.size()) {String mobile = mobiles.get(i);request.setMobile(mobile);OapiUserGetByMobileResponse execute = client.execute(request, token);logger.debug("当前获取的userId为:{}", execute.getUserid());logger.debug(execute.getErrcode());if (!"0".equals(execute.getErrorCode())) {logger.error("获取userId失败,跳过当前操作,获取的手机号码为:{},错误信息为:{}", mobile, execute.getErrmsg());i++;continue;}userIds[i] = execute.getUserid();i++;}logger.debug("已获取全部userId,{}", Arrays.toString(userIds));return ArrayUtil.join(userIds, ",");}
}

3. 设置定时任务

设置每天8点发送钉钉消息定时任务,
若依框架在系统监控-定时任务下配置


后端指定调用的方法

这里测试定时任务没有问题,就可以写异步任务-发送钉钉消息了

4. 异步任务-发送钉钉消息

5. 配置白名单

代码

package com.tn.grms.task;import com.tn.grmsmon.utils.StringUtils;
import com.tn.grms.stock.domain.GrmsStockRecordItem;
import com.tn.grms.stock.mapper.GrmsStockRecordItemMapper;
import com.tn.grms.stock.tools.GrmsAsynTaskService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;import java.util.List;/*** 定时任务调度测试** @author ruoyi*/
@Component("grmsTask")
public class GrmsTask
{private static final Logger logger = LogManager.getLogger(GrmsTask.class);@Autowiredprivate GrmsStockRecordItemMapper grmsStockRecordItemMapper;@Autowiredprivate GrmsAsynTaskService grmsAsynTaskService;public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i){System.out.println(StringUtils.format("执行多参方法: 字符串类型{},布尔类型{},长整型{},浮点型{},整形{}", s, b, l, d, i));}public void ryParams(String params){System.out.println("执行有参方法:" + params);}public static void ryNoParams(){System.out.println("执行无参方法");}/*** 发送钉钉消息提醒*/public void willExpireProductRemind() {// 查询将到期列表List<GrmsStockRecordItem> willExpireList = grmsStockRecordItemMapper.selectGrmsStockRecordItemWillExpire();if (!CollectionUtils.isEmpty(willExpireList)){try {grmsAsynTaskService.sendMessageForWillExpire(willExpireList);}catch (Exception e){e.printStackTrace();logger.info("异步发送钉钉消息异常");}}else {logger.info("将到期列表查询为空,不发送钉钉消息提醒");}}
}
package com.tn.grms.stock.tools;import com.tn.grmsmon.core.domain.entity.SysUser;
import com.tn.grmsmon.utils.DingtalkUtils;
import com.tn.grms.stock.domain.GrmsStockRecordItem;
import com.tn.grms.system.service.ISysUserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;import java.util.ArrayList;
import java.util.List;/*** 异步任务服务*/
@Component
public class GrmsAsynTaskService {private static final Logger logger = LogManager.getLogger(GrmsAsynTaskService.class);@Autowiredprivate ISysUserService iSysUserService;@Asyncpublic void sendMessageForWillExpire(List<GrmsStockRecordItem> willExpireList) {try{for (GrmsStockRecordItem item : willExpireList){Long time = System.currentTimeMillis();SysUser user = iSysUserService.selectUserByUserName(item.getCreateBy());if(!ObjectUtils.isEmpty(user)){// grms系统注册用户时,phone填写与钉钉登录电话号码保持一致,如果用户在本系统没有填写 phone,就不能收到钉钉消息提醒List<String> phones = new ArrayList<>();;phones.add(user.getPhonenumber());StringBuilder message = new StringBuilder();// 您好,grms系统用户:admin, xxx批次,xxx,保质期到 xxx 截止,即将过期,请尽快优先处理message.append("您好,grms系统用户:").append(user.getUserName()).append(",").append(item.getBatchNo()).append("批次,").append(item.getProName()).append(",保质期到").append(item.getExpiryDate()).append("截止,即将过期,请尽快优先处理!时间戳").append(String.valueOf(time));DingtalkUtils.sendMessage(message.toString(), phones);}else {logger.info("未查询到将到期物品,对应的入库操作人信息");}}}catch (Exception e){e.printStackTrace();}}
}

更多推荐

【若依框架】定时任务调用异步服务,实现每天定时发送钉钉消息通知

本文发布于:2024-02-26 23:39:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1704408.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:框架   消息   通知

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!