首页 > 其他分享 >【若依框架】定时任务调用异步服务,实现每天定时发送钉钉消息通知

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

时间:2023-05-20 09:56:05浏览次数:35  
标签:异步 String 若依 token new import 定时 com logger

 

https://blog.csdn.net/MS_SONG/article/details/129141498

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

 

后端实现思路

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.grms.common.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 = "https://oapi.dingtalk.com/robot/send?access_token=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 = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2";
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("https://oapi.dingtalk.com/gettoken");
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("https://oapi.dingtalk.com/user/get_by_mobile");
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.grms.common.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);

@Autowired
private GrmsStockRecordItemMapper grmsStockRecordItemMapper;

@Autowired
private 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.grms.common.core.domain.entity.SysUser;
import com.tn.grms.common.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);

@Autowired
private ISysUserService iSysUserService;


@Async
public 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();
}
}
}

 

 

 

标签:异步,String,若依,token,new,import,定时,com,logger
From: https://www.cnblogs.com/chuangsi/p/17416807.html

相关文章

  • C#异步编程之async/await
    https://blog.csdn.net/wulex/article/details/127380403  异步、多线程的区别 异步:属于通信的范畴,在发出消息当下不等待对方回应,便开始继续自己的任务。所以c#的很多_异步_操作都在io、socket这些类库下面,都是通信性质的类库, io可以理解向系统内核发送文件......
  • jmeter性能测试-定时器
    1.固定定时器:ConstantTimer官方介绍功能:通过该定时器,可以对每一个线程延迟固定的时间。个人实践:如果想通过该定时器来控制吞吐量来达到想要的TPS不是很可靠。2.同步定时器:SynchronizingTimer官方介绍功能:通过该定时器,可以在某一逻辑点模拟创建大负载量进行测试。原理:......
  • 使用Celery实现计划任务与异步任务
    前言Celery是一个开源的分布式任务队列系统,用于处理异步任务和分布式任务调度。使用消息代理(如RabbitMQ、Redis)来实现任务队列和消息传递。在使用Python开发web应用过程中,经常使用Celery完成两种任务需求:异步任务。将任务提交到任务队列中,然后继续处理其他任务,而不必等待任务完成。......
  • 异步CDC及异步FIFO分享
    分享两篇很棒的论文:1.《ClockDomainCrossing(CDC)Design&VerificationTechniquesUsingSystemVerilog》http://www.sunburst-design.com/papers/CummingsSNUG2008Boston_CDC.pdf2.《SimulationandSynthesisTechniquesforAsynchronousFIFO......
  • C# Async异步
    原文链接:https://blog.csdn.net/zuheyawen/article/details/99863588转载连接:https://www.cnblogs.com/wcrBlog/p/11690460.html前言C#异步编程有几种实现方式,异步方法就是其中的一种。异步方法是C#5.0才有的新特性,主要采用async、await关键字声明为异步方法,完成对方法的异......
  • 异步爬虫
    异步爬虫多线程多进程协程多线程与多进程进程:运行中的程序,每次我们执行一个程序,操作系统对自动的为这个程序准备一些必要的资源(如:分配内存,创建一个能够执行的线程)线程:程序内,可以直接被CPU调度的执行过程,是操作系统能够进行运算调度的最小单位,它被包含在进程之中,是进程中的......
  • Centos7 设置定时任务
    原文链接:https://blog.csdn.net/weixin_38565317/article/details/127039873配置定时任务1.下载定时任务依赖yuminstallcrontabs12.设置为可用状态并启动systemctlenablecrondsystemctlstartcrond12如图所示,定时任务程序安装过程:3.配置定时任务文件vim/etc/crontab1如......
  • 关于razor 异步调用的一些新鲜点,记录
    很久没有写razor了,今天在做一个小工具的时候,通过查资料等,学习了新东西。关于razor通过js异步提交的问题。(不是访问特定的webapi)1.razro自带防 XSRF攻击,因而,调用后台的OnGet或者Onpost方法的时候,都会返回400错误。第一,razor页面,带上 @Html.AntiForgeryToken()第二,在startu......
  • win10定时开关机(很多地方总结的定时开机不生效),要用主板bios设置才可以
    1.定时关机(可以使用windows中计划任务)1.此电脑右键-->管理-->系统工具-->任务计划程序库-->右侧创建基本任务2.名称:定时关机,触发器:每天,开始时间2023/05/1817:30:00,启动程序:浏览选择C:\Windows\System32\shutdown.exe,参数:-s 2.定时开机(系统中设置开机,肯定不行。......
  • GitHub创建Github Action流水线来定时发送天气预报给email
     1、基本原理curlwttr.incurlwttr.in/Shanghaicurlwttr.in/wuhan   2、参考文章基于GITHUBACTION的定时任务,真香!https://blog.csdn.net/qq_40748336/article/details/110749375上文参考的文章GitHubActions入门教程_阮一峰http://www.ruanyifeng.com/blo......