feat(推流管理):推流、拉流地址管理功能

This commit is contained in:
2025-04-29 20:10:03 +08:00
parent 812cc5b4e3
commit e824862582
21 changed files with 738 additions and 98 deletions
@@ -0,0 +1,20 @@
package com.central.order.controller;
import com.central.order.service.LiveStreamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/live")
public class LiveStreamController {
@Autowired
private LiveStreamService liveStreamService;
@GetMapping("/stream-urls")
public Map<String, String> getStreamUrls(@RequestParam String deviceId) {
return liveStreamService.generateStreamUrls(deviceId);
}
}
@@ -0,0 +1,54 @@
package com.central.order.controller;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.order.model.WxMessageRecord;
import com.central.order.service.IWxMessageRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.util.Map;
@Slf4j
@RestController
@Tag(name = "微信消息记录管理")
@RequestMapping("/wx/message")
public class WxMessageRecordController {
@Autowired
private IWxMessageRecordService messageRecordService;
@Operation(summary = "分页查询消息记录")
@GetMapping("/records")
public PageResult<WxMessageRecord> records(@RequestParam Map<String, Object> params) {
return messageRecordService.findRecords(params);
}
@Operation(summary = "获取消息统计")
@GetMapping("/statistics")
public Result<Map<String, Object>> statistics(
@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
if (startTime == null) {
startTime = LocalDateTime.now().minusDays(7);
}
if (endTime == null) {
endTime = LocalDateTime.now();
}
return Result.succeed(messageRecordService.getStatistics(startTime, endTime));
}
@Operation(summary = "获取失败消息记录")
@GetMapping("/failed")
public Result getFailedRecords() {
return Result.succeed(messageRecordService.getFailedRecords());
}
}
@@ -62,7 +62,7 @@ public class WxMessageHandler {
openId, msgId, status);
// 更新消息发送状态
updateMessageStatus(openId, msgId, status);
updateMessageStatus(openId, msgId, status.equals("SUCCESS")?1:0);
} catch (Exception e) {
log.error("处理模板消息发送结果事件失败", e);
@@ -97,13 +97,12 @@ public class WxMessageHandler {
/**
* 更新消息发送状态
*/
private void updateMessageStatus(String openId, String msgId, String status) {
private void updateMessageStatus(String openId, String msgId, Integer status) {
try {
WxMessageRecord record = WxMessageRecord.builder()
.openId(openId)
.msgId(msgId)
.status(status)
.updateTime(LocalDateTime.now())
.build();
// TODO: 调用消息记录服务更新状态
@@ -0,0 +1,9 @@
package com.central.order.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.order.model.WxMessageRecord;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface WxMessageRecordMapper extends BaseMapper<WxMessageRecord> {
}
@@ -1,14 +1,12 @@
package com.central.order.model;
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.IdType;
import java.time.LocalDateTime;
import java.util.Date;
@Data
@Builder
@@ -22,8 +20,13 @@ public class WxMessageRecord {
private String templateId;
private String msgId;
private String content;
private String status;
private Integer status;
private String errorMsg;
private LocalDateTime createTime;
private LocalDateTime updateTime;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
//租户ID
private Long tenantId;
}
@@ -0,0 +1,36 @@
package com.central.order.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.common.model.PageResult;
import com.central.order.model.WxMessageRecord;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
public interface IWxMessageRecordService extends IService<WxMessageRecord> {
/**
* 分页查询消息记录
*/
PageResult<WxMessageRecord> findRecords(Map<String, Object> params);
/**
* 保存消息记录
*/
void saveRecord(String openId, String templateId, String content, String msgId, Integer status);
/**
* 更新消息状态
*/
void updateStatus(String msgId, Integer status, String errorMsg);
/**
* 获取时间范围内的发送统计
*/
Map<String, Object> getStatistics(LocalDateTime startTime, LocalDateTime endTime);
/**
* 获取失败的消息记录
*/
List<WxMessageRecord> getFailedRecords();
}
@@ -0,0 +1,41 @@
package com.central.order.service;
import com.central.order.util.TencentLiveUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class LiveStreamService {
@Value("${tencent.live.push-domain}")
private String pushDomain;
@Value("${tencent.live.play-domain}")
private String playDomain;
@Value("${tencent.live.app-name}")
private String appName;
@Value("${tencent.live.key}")
private String key;
@Value("${tencent.live.expire-seconds:3600}")
private long expireSeconds;
/**
* 生成设备推流和拉流地址
*/
public Map<String, String> generateStreamUrls(String deviceId) {
long expire = System.currentTimeMillis() / 1000 + expireSeconds;
String pushUrl = TencentLiveUtil.generatePushUrl(pushDomain, appName, deviceId, key, expire);
String playRtmpUrl = TencentLiveUtil.generatePlayUrl(playDomain, appName, deviceId, "rtmp");
String playFlvUrl = TencentLiveUtil.generatePlayUrl(playDomain, appName, deviceId, "flv");
String playM3u8Url = TencentLiveUtil.generatePlayUrl(playDomain, appName, deviceId, "m3u8");
Map<String, String> result = new HashMap<>();
result.put("pushUrl", pushUrl);
result.put("playRtmpUrl", playRtmpUrl);
result.put("playFlvUrl", playFlvUrl);
result.put("playM3u8Url", playM3u8Url);
return result;
}
}
@@ -0,0 +1,112 @@
package com.central.order.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.common.model.PageResult;
import com.central.order.enums.CommonStatus;
import com.central.order.mapper.WxMessageRecordMapper;
import com.central.order.model.WxMessageRecord;
import com.central.order.service.IWxMessageRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class WxMessageRecordServiceImpl extends ServiceImpl<WxMessageRecordMapper, WxMessageRecord> implements IWxMessageRecordService {
@Override
public PageResult<WxMessageRecord> findRecords(Map<String, Object> params) {
Page<WxMessageRecord> page = new Page<>(MapUtils.getInteger(params, "page", 1),
MapUtils.getInteger(params, "limit", 10));
QueryWrapper<WxMessageRecord> wrapper = new QueryWrapper<>();
// 添加查询条件
String openId = MapUtils.getString(params, "openId");
if (openId != null) {
wrapper.eq("open_id", openId);
}
Integer status = MapUtils.getInteger(params, "status");
if (status != null) {
wrapper.eq("status", status);
}
String startTime = MapUtils.getString(params, "startTime");
if (startTime != null) {
wrapper.ge("create_time", startTime);
}
String endTime = MapUtils.getString(params, "endTime");
if (endTime != null) {
wrapper.le("create_time", endTime);
}
wrapper.orderByDesc("create_time");
Page<WxMessageRecord> recordPage = this.page(page, wrapper);
return PageResult.<WxMessageRecord>builder()
.data(recordPage.getRecords())
.count(recordPage.getTotal())
.build();
}
@Override
public void saveRecord(String openId, String templateId, String content, String msgId, Integer status) {
WxMessageRecord record = WxMessageRecord.builder()
.openId(openId)
.templateId(templateId)
.content(content)
.msgId(msgId)
.status(status)
.build();
this.save(record);
}
@Override
public void updateStatus(String msgId, Integer status, String errorMsg) {
WxMessageRecord record = new WxMessageRecord();
record.setStatus(status);
record.setErrorMsg(errorMsg);
this.update(record, new QueryWrapper<WxMessageRecord>()
.eq("msg_id", msgId));
}
@Override
public Map<String, Object> getStatistics(LocalDateTime startTime, LocalDateTime endTime) {
QueryWrapper<WxMessageRecord> wrapper = new QueryWrapper<>();
wrapper.between("create_time", startTime, endTime);
Map<String, Object> statistics = new HashMap<>();
// 总发送量
long total = this.count(wrapper);
statistics.put("total", total);
// 发送成功量
long success = this.count(wrapper.clone().eq("status", CommonStatus.ENABLE.getId()));
statistics.put("success", success);
// 发送失败量
long failed = this.count(wrapper.clone().eq("status", CommonStatus.UNABLE.getId()));
statistics.put("failed", failed);
return statistics;
}
@Override
public List<WxMessageRecord> getFailedRecords() {
QueryWrapper<WxMessageRecord> wrapper = new QueryWrapper<>();
wrapper.eq("status", CommonStatus.UNABLE.getId())
.orderByDesc("create_time");
return this.list(wrapper);
}
}
@@ -1,7 +1,11 @@
package com.central.order.service.impl;
import com.central.common.exception.BusinessException;
import com.central.order.config.TencentPayProperties;
import com.central.order.config.WxMpProperties;
import com.central.order.enums.CommonStatus;
import com.central.order.model.WxMessageRecord;
import com.central.order.service.IWxMessageRecordService;
import com.central.order.service.IWxTemplateMessageService;
import com.central.order.service.IWxUserService;
import lombok.RequiredArgsConstructor;
@@ -36,6 +40,11 @@ public class WxTemplateMessageServiceImpl implements IWxTemplateMessageService {
@Autowired
private IWxUserService wxUserService;
@Autowired
private TencentPayProperties tencentPayProperties;
@Autowired
private IWxMessageRecordService wxMessageRecordService;
@Override
@Retryable(value = WxErrorException.class, maxAttempts = 3, backoff = @Backoff(delay = 1000, multiplier = 2))
public void sendPaymentSuccessNotice(String unionId, String orderNo, String tourismName,
@@ -56,11 +65,15 @@ public class WxTemplateMessageServiceImpl implements IWxTemplateMessageService {
.toUser(openId)
.templateId(wxMpProperties.getTemplateId().getPaymentSuccess())
.data(Arrays.asList(
new WxMpTemplateData("thing2", tourismName+"提示:您当前排在第"+rank+"位!"),
new WxMpTemplateData("thing2", tourismName+"提示: 您当前排在第"+rank+"位!"),
new WxMpTemplateData("time3", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))),
new WxMpTemplateData("character_string1", orderNo),
new WxMpTemplateData("amount4", "19.90")
new WxMpTemplateData("character_string1", orderNo)
// new WxMpTemplateData("amount4", "19.90")
))
.miniProgram(new WxMpTemplateMessage.MiniProgram(
tencentPayProperties.getAppId(),
"pages/index/index",
true))
.build();
// 发送消息并获取消息ID
@@ -70,7 +83,7 @@ public class WxTemplateMessageServiceImpl implements IWxTemplateMessageService {
log.info("模板消息发送成功: openId={}, orderNo={}, msgId={}", openId, orderNo, msgId);
// 保存发送记录
saveMessageRecord(openId, orderNo, msgId, templateMessage);
saveMessageRecord(openId, msgId, templateMessage);
} catch (WxErrorException e) {
log.error("发送模板消息失败: unionId={}, orderNo={}, errorCode={}, errorMsg={}",
@@ -93,9 +106,65 @@ public class WxTemplateMessageServiceImpl implements IWxTemplateMessageService {
return amount.setScale(2, RoundingMode.HALF_UP).toString() + "元";
}
private void saveMessageRecord(String openId, String orderNo, String msgId,
WxMpTemplateMessage templateMessage) {
// TODO: 实现消息发送记录保存逻辑
private void saveMessageRecord(String openId, String msgId, WxMpTemplateMessage templateMessage) {
try {
// 1. 提取模板消息内容
String content = extractMessageContent(templateMessage);
// 2. 构建消息记录
WxMessageRecord record = WxMessageRecord.builder()
.openId(openId)
.templateId(templateMessage.getTemplateId())
.msgId(msgId)
.content(content)
.status(CommonStatus.ENABLE.getId())
.build();
// 3. 保存记录
log.info("准备保存微信消息记录: openId={}, msgId={}, templateId={}",
openId, msgId, templateMessage.getTemplateId());
wxMessageRecordService.save(record);
log.info("微信消息记录保存成功: msgId={}", msgId);
} catch (Exception e) {
log.error("保存微信消息记录失败: openId={}, msgId={}, error={}",
openId, msgId, e.getMessage(), e);
// 这里选择不抛出异常,因为消息已经发送成功,记录保存失败不应影响主流程
}
}
/**
* 提取模板消息内容
*/
private String extractMessageContent(WxMpTemplateMessage templateMessage) {
StringBuilder content = new StringBuilder();
// 提取小程序信息
if (templateMessage.getMiniProgram() != null) {
content.append("小程序信息:")
.append("appid=").append(templateMessage.getMiniProgram().getAppid())
.append(", path=").append(templateMessage.getMiniProgram().getPagePath())
.append("\n");
}
// 提取模板数据
if (templateMessage.getData() != null) {
content.append("模板数据:\n");
templateMessage.getData().forEach(data ->
content.append(data.getName())
.append("=")
.append(data.getValue())
.append("\n")
);
}
// 如果内容过长,进行截断
String result = content.toString();
if (result.length() > 500) { // 假设数据库字段长度限制为500
result = result.substring(0, 497) + "...";
}
return result;
}
@Recover
@@ -1,17 +1,17 @@
package com.central.order.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.central.order.service.IWxUserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpUserService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Slf4j
@Service
@@ -20,68 +20,53 @@ public class WxUserServiceImpl implements IWxUserService {
@Autowired
private WxMpService wxMpService;
@Autowired
private RestTemplate restTemplate;
@Override
@Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000))
@Retryable(value = WxErrorException.class, maxAttempts = 3, backoff = @Backoff(delay = 2000, multiplier = 2))
public String getMpOpenIdByUnionId(String targetUnionId) {
try {
String accessToken = wxMpService.getAccessToken();
log.info("开始查找 unionId: {} 对应的 openId", targetUnionId);
// 1. 获取服务号所有关注者 openid 列表
WxMpUserService userService = wxMpService.getUserService();
String nextOpenId = null;
do {
String userListUrl = String.format("https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s&next_openid=%s",
accessToken, nextOpenId == null ? "" : nextOpenId);
ResponseEntity<String> response = restTemplate.getForEntity(userListUrl, String.class);
JSONObject userList = JSON.parseObject(response.getBody());
if (userList.getJSONObject("data") == null) {
log.warn("No users found in the official account");
// 获取关注者列表
WxMpUserList userList = userService.userList(nextOpenId);
if (userList == null || userList.getCount() == 0) {
log.warn("未找到关注用户");
break;
}
JSONArray openids = userList.getJSONObject("data").getJSONArray("openid");
// 2. 批量获取用户信息(每次最多100个)
for (int i = 0; i < openids.size(); i += 100) {
int endIndex = Math.min(i + 100, openids.size());
JSONArray batch = new JSONArray();
for (int j = i; j < endIndex; j++) {
JSONObject user = new JSONObject();
user.put("openid", openids.getString(j));
user.put("lang", "zh_CN");
batch.add(user);
}
JSONObject postData = new JSONObject();
postData.put("user_list", batch);
String batchUrl = String.format("https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=%s", accessToken);
ResponseEntity<String> batchResponse = restTemplate.postForEntity(batchUrl, postData, String.class);
JSONObject batchResult = JSON.parseObject(batchResponse.getBody());
JSONArray userInfoList = batchResult.getJSONArray("user_info_list");
for (int j = 0; j < userInfoList.size(); j++) {
JSONObject userInfo = userInfoList.getJSONObject(j);
if (targetUnionId.equals(userInfo.getString("unionid"))) {
log.info("Found matching openid for unionid {}: {}", targetUnionId, userInfo.getString("openid"));
return userInfo.getString("openid");
// 批量获取用户信息
for (String openId : userList.getOpenids()) {
try {
WxMpUser userInfo = userService.userInfo(openId);
if (targetUnionId.equals(userInfo.getUnionId())) {
log.info("找到匹配的 openId: {} 对应的 unionId: {}", openId, targetUnionId);
return openId;
}
} catch (WxErrorException e) {
log.warn("获取用户 {} 信息失败: {}", openId, e.getMessage());
continue; // 单个用户获取失败继续处理下一个
}
}
nextOpenId = userList.getString("next_openid");
nextOpenId = userList.getNextOpenid();
} while (nextOpenId != null && !nextOpenId.isEmpty());
log.warn("No matching openid found for unionid: {}", targetUnionId);
log.warn("未找到 unionId: {} 对应的 openId", targetUnionId);
return null;
} catch (Exception e) {
log.error("Error getting MP openid for unionid {}: {}", targetUnionId, e.getMessage(), e);
throw new RuntimeException("Failed to get MP openid", e);
} catch (WxErrorException e) {
log.error("获取 MP openId 失败,unionId: {},错误: {}", targetUnionId, e.getMessage(), e);
throw new RuntimeException("获取 MP openId 失败", e);
}
}
@Recover
public String recover(Exception e, String targetUnionId) {
log.error("获取 MP openId 重试耗尽,unionId: {},最终错误: {}", targetUnionId, e.getMessage());
// 可以在这里添加告警通知
return null;
}
}
@@ -0,0 +1,30 @@
package com.central.order.util;
import org.apache.commons.codec.digest.DigestUtils;
public class TencentLiveUtil {
/**
* 生成推流地址
*/
public static String generatePushUrl(String pushDomain, String appName, String streamName, String key, long expireTime) {
String txTime = Long.toHexString(expireTime).toUpperCase();
String txSecret = DigestUtils.md5Hex(key + streamName + txTime).toLowerCase();
return String.format("rtmp://%s/%s/%s?txSecret=%s&txTime=%s", pushDomain, appName, streamName, txSecret, txTime);
}
/**
* 生成拉流地址
*/
public static String generatePlayUrl(String playDomain, String appName, String streamName, String type) {
switch (type.toLowerCase()) {
case "flv":
return String.format("http://%s/%s/%s.flv", playDomain, appName, streamName);
case "m3u8":
return String.format("http://%s/%s/%s.m3u8", playDomain, appName, streamName);
case "rtmp":
default:
return String.format("rtmp://%s/%s/%s", playDomain, appName, streamName);
}
}
}
@@ -60,6 +60,12 @@ tencent:
async-pool-size: 5
api:
profit-sharing-url: https://api.mch.weixin.qq.com/v3/profitsharing/orders
live:
push-domain: 208280.push.tlivecloud.com
play-domain: goflytec.com
app-name: live
key: 06b20e5b7d637c1128fa1b48ea91a13e
expire-seconds: 3600
file:
oss-url: goflyapp.oss-cn-beijing.aliyuncs.com
cdn-url: cdn.goflytec.com