package com.yingji.utils; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.http.HttpRequest; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.yingji.redis.RedisCache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.time.LocalDate; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; /** * 短信通知工具类 * * @author wu * @since 2024/9/24 10:18 */ @Component public class SmsUtil { public static final Logger log = LoggerFactory.getLogger(SmsUtil.class); @Resource private RedisCache redisCache; /** * 获取短信接口token * * @return token */ public String getSmsToken() { Map bodyMap = new HashMap<>(); bodyMap.put("uid", "yjglj_yjjyszzh"); bodyMap.put("pwd", "f604d2d6de51573b5cef5c95c11ffabe"); String bodyJson = JSONUtil.toJsonStr(bodyMap); String responseStr = HttpRequest.post("http://2.46.42.43:80/admin-api/sms/token") .body(bodyJson) .execute() .body(); JSONObject responseJson = JSONUtil.parseObj(responseStr); log.error("----------------------------短信token======================"); log.error("短信token: " + JSONUtil.toJsonStr(responseJson)); return (String) responseJson.get("data"); } /** * 发送短信 * * @param content 短信内容 * @param tel 手机号多个使用,拼接 * @param errorMes 异常通知的类别 即redis的key */ public void sendSms(String content, String tel, String errorMes) { if (errorMes != null) { Integer minutes = redisCache.getCacheObject(errorMes); if (minutes == null) { redisCache.setCacheObject(errorMes, 1, 10, TimeUnit.MINUTES); return; } if (minutes < 10) { redisCache.setCacheObject(errorMes, minutes + 1); return; } } // 限制每种tel每天只能发一次短信 Map dataKey = redisCache.getCacheMap("dataKey"); if (CollectionUtil.isNotEmpty(dataKey)) { LocalDate sendDate = (LocalDate) dataKey.get(content); if (LocalDate.now().equals(sendDate)) { return; } else { dataKey.put(content, LocalDate.now()); redisCache.setCacheMap("dataKey", dataKey); } } else { Map map = new HashMap<>(); map.put(content, LocalDate.now()); redisCache.setCacheMap("dataKey", map); } String token = getSmsToken(); Map bodyMap = new HashMap<>(); bodyMap.put("uid", "yjglj_yjjyszzh"); bodyMap.put("pwd", "f604d2d6de51573b5cef5c95c11ffabe"); bodyMap.put("extensionNo", "2559"); if (StrUtil.isNotEmpty(tel)) { bodyMap.put("tel", tel); } else { bodyMap.put("tel", "18870257135,18261462112,15850922852,18112760590"); } bodyMap.put("content", "市应急局提醒:" + content); String bodyJson = JSONUtil.toJsonStr(bodyMap); log.error("bodyJson: " + bodyJson); String responseStr = HttpRequest.post("http://2.46.42.43:80/admin-api/sms/send") .header("Authorization", "Bearer " + token) .body(bodyJson) .execute() .body(); log.error("----------------------------短信响应======================"); log.error("短信: " + JSONUtil.toJsonStr(responseStr)); } }