package com.zy.asrs.service; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.zy.asrs.domain.NotifyDto; import com.zy.asrs.entity.HttpRequestLog; import com.zy.common.utils.HttpHandler; import com.zy.common.utils.RedisUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import java.util.Date; /** * 异步通知服务 * 用于异步发送HTTP通知请求,避免阻塞定时器线程 */ @Service @Slf4j public class NotifyAsyncService { @Autowired private RedisUtil redisUtil; @Autowired private HttpRequestLogService httpRequestLogService; /** * 异步发送通知 * * @param notifyUri 通知URI * @param notifyUriPath 通知路径 * @param key Redis键 * @param notifyDto 通知数据 */ @Async public void sendNotifyAsync(String notifyUri, String notifyUriPath, String key, NotifyDto notifyDto) { HttpRequestLog httpRequestLog = new HttpRequestLog(); httpRequestLog.setName(notifyUri + notifyUriPath); httpRequestLog.setRequest(JSON.toJSONString(notifyDto)); httpRequestLog.setCreateTime(new Date()); boolean success = false; try { // 触发通知 String response = new HttpHandler.Builder() .setUri(notifyUri) .setPath(notifyUriPath) .setJson(JSON.toJSONString(notifyDto)) .build() .doPost(); httpRequestLog.setResponse(response); JSONObject jsonObject = JSON.parseObject(response); Integer code = jsonObject.getInteger("code"); if (code == 200) { // 通知成功 redisUtil.del(key); success = true; } } catch (Exception e) { log.error("异步通知失败, key={}", key, e); } finally { // 保存记录 httpRequestLogService.insert(httpRequestLog); } if (!success) { // 通知失败,更新重试次数 handleNotifyFailure(key, notifyDto); } } /** * 处理通知失败的情况 */ private void handleNotifyFailure(String key, NotifyDto notifyDto) { try { int times = notifyDto.getRetryTimes() + 1; if (times >= notifyDto.getFailTimes()) { // 超过次数 redisUtil.del(key); return; } notifyDto.setLastRetryTime(System.currentTimeMillis()); notifyDto.setRetryTimes(times); redisUtil.set(key, notifyDto); } catch (Exception e) { log.error("处理通知失败逻辑异常, key={}", key, e); } } }