UnifiedUserCenterServiceImpl.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. package com.ylx.usercenter.service.impl;
  2. import cn.hutool.core.collection.CollUtil;
  3. import cn.hutool.core.util.ObjUtil;
  4. import cn.hutool.core.util.StrUtil;
  5. import cn.hutool.http.HttpUtil;
  6. import com.alibaba.fastjson.JSON;
  7. import com.alibaba.fastjson.JSONArray;
  8. import com.alibaba.fastjson.JSONObject;
  9. import com.alibaba.fastjson.TypeReference;
  10. import com.ylx.common.core.domain.R;
  11. import com.ylx.common.exception.ServiceException;
  12. import com.ylx.lottery.service.LotteryCountService;
  13. import com.ylx.massage.domain.TWxUser;
  14. import com.ylx.massage.service.TWxUserService;
  15. import com.ylx.usercenter.domain.dto.UnifiedUserCenterDTO;
  16. import com.ylx.usercenter.domain.vo.OneAccountVO;
  17. import com.ylx.usercenter.domain.vo.UnifiedUserCenterResponseVO;
  18. import com.ylx.usercenter.service.UnifiedUserCenterService;
  19. import lombok.extern.slf4j.Slf4j;
  20. import org.springframework.beans.factory.annotation.Value;
  21. import org.springframework.scheduling.annotation.Async;
  22. import org.springframework.stereotype.Service;
  23. import org.springframework.transaction.annotation.Propagation;
  24. import org.springframework.transaction.annotation.Transactional;
  25. import javax.annotation.Resource;
  26. import java.util.Collections;
  27. import java.util.List;
  28. import java.util.Map;
  29. @Slf4j
  30. @Service
  31. public class UnifiedUserCenterServiceImpl implements UnifiedUserCenterService {
  32. @Value("${remote.user-center.base-url}")
  33. private String userCenterBaseUrl;
  34. @Value("${remote.night-fragrance.client-id}")
  35. private String clientId;
  36. // 定义接口路径常量
  37. private static final String QUERY_BIND_PATH = "/userApp/queryBind";
  38. private static final String BIND_PATH = "/userApp/bind";
  39. private static final String UNBIND_PATH = "/userApp/unbind";
  40. private static final String QUERY_CLIENTS_PATH = "/userApp/queryClients";
  41. private static final int DEFAULT_TIMEOUT = 5000; // 5秒超时
  42. @Resource
  43. private TWxUserService wxUserService;
  44. @Resource
  45. private LotteryCountService lotteryCountService;
  46. @Override
  47. public R<?> queryBind(UnifiedUserCenterDTO dto) {
  48. // 只需要关注业务路径和日志描述即可
  49. return executePost(QUERY_BIND_PATH, dto, "查询用户绑定信息");
  50. }
  51. @Override
  52. public R<?> bind(UnifiedUserCenterDTO dto) {
  53. try {
  54. // 1.检验参数信息
  55. validateDto(dto);
  56. // 2.获取用户信息
  57. TWxUser wxUser = this.wxUserService.getById(dto.getTargetUserId());
  58. if (ObjUtil.isEmpty(wxUser)) {
  59. log.error("用户信息不存在, userId: {}", dto.getTargetUserId());
  60. throw new ServiceException("用户信息不存在");
  61. }
  62. // 3.添加用户绑定信息
  63. R<?> remoteResult = executePost(BIND_PATH, dto, "添加用户绑定信息");
  64. // 4. 判断绑定成功
  65. if (ObjUtil.notEqual(remoteResult.getCode(), 200)) {
  66. log.error("远程绑定失败, userId: {}, msg: {}", dto.getTargetUserId(), remoteResult.getMsg());
  67. return R.fail("用户绑定失败:" + remoteResult.getMsg());
  68. }
  69. // 5. 更新本地数据库(独立事务)
  70. updateUserBindStatus(dto,wxUser);
  71. // 6. 同步抽奖次数(异步处理)
  72. syncLotteryCount(dto);
  73. return R.ok(remoteResult.getData(), "用户绑定成功");
  74. } catch (ServiceException e) {
  75. log.error("用户绑定业务异常, userId:{}", dto.getTargetUserId(), e);
  76. throw e;
  77. } catch (Exception e) {
  78. log.error("用户绑定系统异常, userId:{}", dto.getTargetUserId(), e);
  79. throw new ServiceException("系统异常,请稍后重试");
  80. }
  81. }
  82. @Override
  83. public R<?> unbind(UnifiedUserCenterDTO dto) {
  84. validateDto(dto);
  85. return executePost(UNBIND_PATH, dto, "解除用户绑定信息");
  86. }
  87. @Override
  88. public OneAccountVO queryClients(String uuid) {
  89. log.info("调用一账通查询平台绑定信息:{}", uuid);
  90. return this.queryClientsByUuid(uuid);
  91. }
  92. /**
  93. * 通用 HTTP POST 请求执行模板
  94. */
  95. private R<?> executePost(String path, UnifiedUserCenterDTO dto, String logDesc) {
  96. try {
  97. // 1. 构建 URL
  98. String url = userCenterBaseUrl + path;
  99. // 2. 转换参数
  100. String jsonParam = JSON.toJSONString(dto);
  101. // 3. 发送请求
  102. String result = HttpUtil.post(url, jsonParam);
  103. // 4. 校验结果
  104. if (StrUtil.isEmpty(result)) {
  105. throw new RuntimeException(logDesc + "失败:接口返回空结果");
  106. }
  107. // 5. 解析结果
  108. UnifiedUserCenterResponseVO response = JSON.parseObject(
  109. result,
  110. new TypeReference<UnifiedUserCenterResponseVO>() {
  111. }
  112. );
  113. // 4. 处理业务状态
  114. if (!response.isSuccess()) {
  115. log.warn("{}失败: data={},code={}, msg={}", logDesc, response.getData(), response.getCode(), response.getMessage());
  116. return R.fail(response.getData(), response.getMessage());
  117. }
  118. Object dataObj = response.getData();
  119. // 情况 A: data 是布尔值 false (虽然 code=0,但没数据)
  120. if (dataObj instanceof Boolean) {
  121. log.info("接口返回 data 为布尔值: {}", dataObj);
  122. return R.ok(response.getData());
  123. }
  124. // 情况 B: data 是 JSONObject (例如: { "userClients": [...] })
  125. if (dataObj instanceof JSONObject) {
  126. JSONObject jsonObject = (JSONObject) dataObj;
  127. // 优先尝试获取 "userClients" 字段 (针对当前截图的场景)
  128. Object userClientsObj = jsonObject.get("userClients");
  129. if (userClientsObj instanceof JSONArray) {
  130. JSONArray userClientsArray = (JSONArray) userClientsObj;
  131. log.info("获取到用户客户端数量: {}", userClientsArray.size());
  132. // 如果需要转为具体的 List<UserClientVO>,可以在这里做转换
  133. return R.ok(userClientsArray);
  134. }
  135. // 兜底逻辑:如果是其他类型的 JSONObject (例如查询详情),直接返回整个对象
  136. // 避免数据丢失
  137. return R.ok(jsonObject);
  138. }
  139. // 情况 C: data 是其他类型 (例如直接是一个 String 或 Number)
  140. return R.ok(dataObj);
  141. } catch (Exception e) {
  142. log.error("{}发生异常", logDesc, e);
  143. throw new ServiceException(logDesc + "异常" + e);
  144. }
  145. }
  146. /**
  147. * 参数校验提取
  148. */
  149. private void validateDto(UnifiedUserCenterDTO dto) {
  150. if (StrUtil.isEmpty(dto.getSourceUserId())) {
  151. throw new IllegalArgumentException("源用户ID不能为空");
  152. }
  153. if (StrUtil.isEmpty(dto.getTargetUserId())) {
  154. throw new IllegalArgumentException("目标用户ID不能为空");
  155. }
  156. if (StrUtil.isEmpty(dto.getSourceClientId())) {
  157. throw new IllegalArgumentException("源客户端ID不能为空");
  158. }
  159. if (StrUtil.isEmpty(dto.getTargetClientId())) {
  160. throw new IllegalArgumentException("目标客户端ID不能为空");
  161. }
  162. }
  163. // 独立事务方法
  164. @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
  165. public void updateUserBindStatus(UnifiedUserCenterDTO dto, TWxUser wxUser) {
  166. try {
  167. wxUser.setIsBind(1);
  168. wxUser.setLocalLiveUserId(dto.getSourceUserId());
  169. boolean wxUserBool = this.wxUserService.updateById(wxUser);
  170. if (!wxUserBool) {
  171. log.error("更新用户绑定状态失败, userId: {}", dto.getTargetUserId());
  172. throw new ServiceException("更新用户绑定状态失败");
  173. }
  174. log.info("更新用户绑定一账通信息成功, userId:{}", dto.getTargetUserId());
  175. } catch (Exception e) {
  176. log.error("更新用户绑定状态异常, userId: {}", dto.getTargetUserId(), e);
  177. // 如果本地更新失败,异步调用远程解绑接口进行补偿
  178. asyncCompensateUnbind(dto);
  179. throw e;
  180. }
  181. }
  182. // 异步同步抽奖次数
  183. @Async
  184. @Override
  185. public void syncLotteryCount(UnifiedUserCenterDTO dto) {
  186. try {
  187. boolean lotteryCountBool = this.lotteryCountService.batchAdd(dto);
  188. if (lotteryCountBool) {
  189. log.info("同步用户抽奖次数到本地生活服务成功, userId:{}", dto.getTargetUserId());
  190. } else {
  191. log.warn("同步用户抽奖次数到本地生活服务失败, userId:{}", dto.getTargetUserId());
  192. // 同步失败,记录告警日志
  193. log.error("【告警】同步用户抽奖次数到本地生活服务失败,需要人工处理, userId:{}", dto.getTargetUserId());
  194. }
  195. } catch (Exception e) {
  196. log.error("同步用户抽奖次数到本地生活服务异常, userId:{}", dto.getTargetUserId(), e);
  197. // 异常情况,记录告警日志
  198. log.error("【告警】同步用户抽奖次数到本地生活服务异常,需要人工处理, userId:{}", dto.getTargetUserId(), e);
  199. }
  200. }
  201. @Override
  202. public R<?> bindUpdate(UnifiedUserCenterDTO dto) {
  203. try {
  204. // 1.获取用户信息
  205. TWxUser wxUser = this.wxUserService.getById(dto.getTargetUserId());
  206. if (ObjUtil.isEmpty(wxUser)) {
  207. log.error("用户信息不存在, userId: {}", dto.getTargetUserId());
  208. throw new ServiceException("用户信息不存在");
  209. }
  210. // 2. 更新本地数据库(独立事务)
  211. updateUserBindStatus(dto,wxUser);
  212. // 3. 同步抽奖次数(异步处理)
  213. syncLotteryCount(dto);
  214. log.info("同步用户抽奖次数到本地生活服务成功, userId:{}", dto.getTargetUserId());
  215. return R.ok();
  216. } catch (ServiceException e) {
  217. log.error("同步用户抽奖次数到本地生活服务异常, userId:{}", dto.getTargetUserId(), e);
  218. throw e;
  219. } catch (Exception e) {
  220. log.error("同步用户抽奖次数到本地生活服务异常, userId:{}", dto.getTargetUserId(), e);
  221. throw new ServiceException("系统异常,请稍后重试");
  222. }
  223. }
  224. /**
  225. * 异步补偿:解除用户绑定
  226. * 带重试机制,最多重试3次
  227. */
  228. @Async
  229. public void asyncCompensateUnbind(UnifiedUserCenterDTO dto) {
  230. final int maxRetries = 3;
  231. int retryCount = 0;
  232. boolean success = false;
  233. while (retryCount < maxRetries && !success) {
  234. retryCount++;
  235. try {
  236. log.info("异步补偿:尝试解除用户绑定, userId: {}, 重试次数: {}", dto.getTargetUserId(), retryCount);
  237. executePost(UNBIND_PATH, dto, "补偿:解除用户绑定信息");
  238. log.info("异步补偿:成功解除用户绑定, userId: {}", dto.getTargetUserId());
  239. success = true;
  240. } catch (Exception e) {
  241. log.error("异步补偿:解除用户绑定失败, userId: {}, 重试次数: {}", dto.getTargetUserId(), retryCount, e);
  242. if (retryCount < maxRetries) {
  243. try {
  244. // 等待一段时间后重试
  245. Thread.sleep(1000 * retryCount);
  246. } catch (InterruptedException ie) {
  247. Thread.currentThread().interrupt();
  248. log.error("异步补偿:线程被中断, userId: {}", dto.getTargetUserId(), ie);
  249. break;
  250. }
  251. } else {
  252. // 重试次数用完,记录告警日志
  253. log.error("【告警】异步补偿:解除用户绑定失败,已达最大重试次数,需要人工处理, userId: {}", dto.getSourceUserId(), e);
  254. }
  255. }
  256. }
  257. }
  258. private OneAccountVO queryClientsByUuid(String uuid) {
  259. try {
  260. // 1. 构建请求参数
  261. String url = userCenterBaseUrl + QUERY_CLIENTS_PATH;
  262. Map<String, Object> params = Collections.singletonMap("uuid", uuid);
  263. // 2. 发送请求
  264. String resultJson = HttpUtil.get(url, params, DEFAULT_TIMEOUT);
  265. // 3. 校验结果
  266. if (StrUtil.isEmpty(resultJson)) {
  267. throw new RuntimeException("调用一账通查询平台绑定信息接口失败:接口返回空结果");
  268. }
  269. // 4. 解析结果
  270. UnifiedUserCenterResponseVO<List<OneAccountVO>> response = JSON.parseObject(
  271. resultJson,
  272. new TypeReference<UnifiedUserCenterResponseVO<List<OneAccountVO>>>() {
  273. }
  274. );
  275. // 5. 处理业务状态
  276. if (ObjUtil.isNull(response) || !response.isSuccess()) {
  277. String msg = ObjUtil.isNotNull(response) ? response.getMessage() : "未知错误";
  278. Integer code = ObjUtil.isNotNull(response) ? response.getCode() : -1;
  279. log.warn("调用一账通查询平台绑定信息接口失败: code={}, msg={}", code, msg);
  280. throw new ServiceException("远程接口返回失败: " + msg);
  281. }
  282. // 6. 获取数据列表
  283. List<OneAccountVO> oneAccountVOs = response.getData();
  284. if (CollUtil.isEmpty(oneAccountVOs)) {
  285. log.info("未查询到相关活动数据");
  286. return null;
  287. }
  288. OneAccountVO oneAccount = oneAccountVOs.stream().filter(item -> item.getClientId().equals(clientId)).findFirst().orElse(null);
  289. log.info("成功获取调用一账通查询平台绑定信息: {}", JSON.toJSONString(oneAccount));
  290. return oneAccount;
  291. } catch (ServiceException e) {
  292. // 透传业务异常,不要重复包装
  293. throw e;
  294. } catch (Exception e) {
  295. log.error("调用一账通查询平台绑定信息接口发生系统异常", e);
  296. // 优化点:只抛出消息,不要直接把整个 Exception 对象 toString() 拼接到字符串里
  297. throw new ServiceException("调用一账通查询平台绑定信息接口异常: " + e.getMessage());
  298. }
  299. }
  300. }