1
zj
2025-08-21 9c81d055889b78e57e1b0e4797f9615ac45f9913
ruoyi-admin/src/main/java/com/ruoyi/im/service/impl/ImApiServcieImpl.java
@@ -2,31 +2,56 @@
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netease.nim.server.sdk.core.BizName;
import com.netease.nim.server.sdk.core.YunxinApiHttpClient;
import com.netease.nim.server.sdk.core.YunxinApiResponse;
import com.netease.nim.server.sdk.core.exception.YunxinSdkException;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.im.comm.Result;
import com.ruoyi.im.config.AppAuthConfig;
import com.ruoyi.im.config.DynamicRequestBodyBuilder;
import com.ruoyi.im.config.NeteaseResponse;
import com.ruoyi.im.config.UpdateUserInfoRequest;
import com.ruoyi.im.dto.UpdateUserBusinessDto;
import com.ruoyi.system.domain.UserAccount;
import com.ruoyi.im.service.ImApiServcie;
import com.ruoyi.im.dto.RegisterDto;
import com.ruoyi.system.domain.vo.UserAccountUpdateVo;
import com.ruoyi.system.service.UserAccountService;
import com.ruoyi.im.util.SymmetricCryptoUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
@Service
@Slf4j
@@ -34,8 +59,18 @@
    @Autowired
    private UserAccountService userAccountService;
    // 使用单例客户端,避免重复初始化
    private YunxinApiHttpClient yunxinClient;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    private final YunxinApiHttpClient yunxinClient;
    // 使用构造函数注入(推荐)
    @Autowired
    public ImApiServcieImpl(YunxinApiHttpClient yunxinClient) {
        this.yunxinClient = yunxinClient;
    }
    // 使用并发安全的集合存储正在生成的账号,防止重复
    private final Set<Long> generatingAccounts = Collections.newSetFromMap(new ConcurrentHashMap<>());
@@ -44,17 +79,17 @@
    private final AtomicLong lastTimestamp = new AtomicLong(0);
    private final AtomicLong sequence = new AtomicLong(0);
    @PostConstruct
    public void init() {
        // 初始化云信客户端,只执行一次
        String appkey = AppAuthConfig.DEFAULT_CONFIG.getAppKey();
        String appsecret = AppAuthConfig.DEFAULT_CONFIG.getAppSecret();
        int timeoutMillis = 5000;
    private static final String DEFAULT_PASSWORD = "123456";//批量注册密码
    private static final String ENCRYPTED_PASSWORD = SymmetricCryptoUtil.encryptPassword(DEFAULT_PASSWORD); // 密码加密一次,多次使用
        this.yunxinClient = new YunxinApiHttpClient.Builder(BizName.IM, appkey, appsecret)
                .timeoutMillis(timeoutMillis)
                .build();
    }
    private static final String YUNXIN_CREATE_PATH = "/user/create.action";
    @Value("${netease.im.api-head-portrait-url}")
    private String headPortraitUrl;
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务注解确保操作原子性
@@ -76,18 +111,23 @@
            userAccount.setPhoneNumber(dto.getAccount());
            userAccount.setCloudMessageAccount(dto.getAccount());
            userAccount.setPassword(SymmetricCryptoUtil.encryptPassword(dto.getPassword()));
            userAccount.setCreateTime(new Date());
            userAccount.setNickname(dto.getAccount());
            if (!userAccountService.save(userAccount)) {
                return Result.error("注册失败,请重试");
            }
            // 注册云信账号(远程调用)
            String path = "/user/create.action";
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("accid", dto.getAccount());
            if(StringUtils.isNotEmpty(dto.getName())){
                paramMap.put("name", dto.getName());
            }
            paramMap.put("token", dto.getPassword());
            YunxinApiResponse response = yunxinClient.executeV1Api(path, paramMap);
            YunxinApiResponse response = yunxinClient.executeV1Api(YUNXIN_CREATE_PATH, paramMap);
            // 处理云信响应
            String data = response.getData();
@@ -119,6 +159,7 @@
            return Result.error("注册失败,请重试");
        }
    }
    /**
     * 优化的账号生成方法,使用雪花算法变体提高并发性能
@@ -183,4 +224,328 @@
        // 组合时间戳和序列号,生成9位ID
        return timestamp * 100 + seq;
    }
    /**
     * 更新用户名片
     * @param accountId 用户账号
     * @return 操作结果
     */
    public Map<String, Object> updateUserAvatar(String accountId, UpdateUserBusinessDto dto) {
        Map<String, Object> result = new HashMap<>();
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 生成请求参数
            String nonce = UUID.randomUUID().toString().replace("-", "");
            String curTime = String.valueOf(System.currentTimeMillis() / 1000);
            String checkSum = generateCheckSum(nonce, curTime);
            // 构建请求URL
            String url = headPortraitUrl + "/im/v2/users/" + accountId;
            // 构建请求头
            HttpPatch httpPatch = new HttpPatch(url);
            httpPatch.setHeader("Content-Type", "application/json;charset=utf-8");
            httpPatch.setHeader("AppKey", AppAuthConfig.DEFAULT_CONFIG.getAppKey());
            httpPatch.setHeader("Nonce", nonce);
            httpPatch.setHeader("CurTime", curTime);
            httpPatch.setHeader("CheckSum", checkSum);
            // 构建请求体
            UpdateUserInfoRequest builder = new UpdateUserInfoRequest();
            if(StringUtils.isNotEmpty(dto.getMobile())){
                builder.setMobile(dto.getMobile());
            }else if(StringUtils.isNotEmpty(dto.getName())){
                builder.setName(dto.getName());
            }else if(StringUtils.isNotEmpty(dto.getSign())){
                builder.setSign(dto.getSign());
            }else if(StringUtils.isNotEmpty(dto.getAvatar())){
                builder.setAvatar(dto.getAvatar());
            }
            String body = builder.build();
            String jsonBody = objectMapper.writeValueAsString(body);
            httpPatch.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));
            // 执行请求
            HttpResponse response = httpClient.execute(httpPatch);
            String responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            // 解析响应
            NeteaseResponse neteaseResponse = objectMapper.readValue(responseString, NeteaseResponse.class);
            if (neteaseResponse.isSuccess()) {
                result.put("success", true);
                result.put("message", "头像更新成功");
                result.put("data", neteaseResponse.getData());
            } else {
                result.put("success", false);
                result.put("message", "头像更新失败: " + neteaseResponse.getMsg());
                result.put("errorCode", neteaseResponse.getCode());
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "请求网易云信API失败: " + e.getMessage());
        }
        return result;
    }
    /**
     * 生成校验和
     */
    private String generateCheckSum(String nonce, String curTime) {
        String content = AppAuthConfig.DEFAULT_CONFIG.getAppSecret() + nonce + curTime;
        return DigestUtils.sha1Hex(content);
    }
    @Override
    public AjaxResult updateUserAccount(UserAccountUpdateVo vo) {
        //更新用户名片
        UpdateUserBusinessDto dto = new UpdateUserBusinessDto();
        if(StringUtils.isNotEmpty(vo.getPhoneNumber())){
            dto.setMobile(vo.getPhoneNumber());
        }else if(StringUtils.isNotEmpty(vo.getNickname())){
            dto.setName(vo.getNickname());
        }else if(StringUtils.isNotEmpty(vo.getSignature())){
            dto.setSign(vo.getSignature());
        }
        Map<String, Object> map = updateUserAvatar(vo.getAccountId(), dto);
        //更新用户属性 状态 密码
        if ((Boolean) map.get("success")) {
            AjaxResult ajaxResult = updateAccountProperties(vo.getAccountId(), vo);
            if(ajaxResult.isSuccess()){
                UserAccount userAccount = userAccountService.getById(vo.getId());
                userAccount.setPhoneNumber(vo.getPhoneNumber());
                userAccount.setAccount(vo.getAccountId());
                userAccount.setNickname(vo.getNickname());
                userAccount.setPassword(SymmetricCryptoUtil.encryptPassword(vo.getPassword()));
                userAccount.setSignature(vo.getSignature());
                userAccount.setUpdateTime(new Date());
                userAccountService.updateById(userAccount);
            }else{
                return AjaxResult.error("更新用户属性失败!");
            }
        } else {
            return AjaxResult.error("更新用户名片失败!");
        }
        return AjaxResult.success("更新成功!");
    }
    /**
     * 更新账号属性
     * @param accountId 用户账号ID
     * @return 操作结果
     */
    public AjaxResult updateAccountProperties(String accountId, UserAccountUpdateVo vo) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 生成请求参数
            String nonce = UUID.randomUUID().toString().replace("-", "");
            String curTime = String.valueOf(System.currentTimeMillis() / 1000);
            String checkSum = generateCheckSum(nonce, curTime);
            // 构建请求URL
            String url = headPortraitUrl + "/im/v2/accounts/" + accountId;
            // 构建请求头
            HttpPatch httpPatch = new HttpPatch(url);
            httpPatch.setHeader("Content-Type", "application/json;charset=utf-8");
            httpPatch.setHeader("AppKey", AppAuthConfig.DEFAULT_CONFIG.getAppKey());
            httpPatch.setHeader("Nonce", nonce);
            httpPatch.setHeader("CurTime", curTime);
            httpPatch.setHeader("CheckSum", checkSum);
            // 创建构建器实例
            DynamicRequestBodyBuilder builder = new DynamicRequestBodyBuilder();
            if(null != vo.getStatus() && vo.getStatus() == 0){
                builder.setEnabled(false);
                builder.setNeedKick(true);
            }else if(StringUtils.isNotEmpty(vo.getPassword())){
                builder.setToken(vo.getPassword());
            }
            // 只设置需要的字段
            String body = builder.build();
            String jsonBody = objectMapper.writeValueAsString(body);
            httpPatch.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));
            // 执行请求
            HttpResponse response = httpClient.execute(httpPatch);
            String responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            // 解析响应
            NeteaseResponse neteaseResponse = objectMapper.readValue(responseString, NeteaseResponse.class);
            if (neteaseResponse.isSuccess()) {
                AjaxResult.success("账号属性更新成功");
            } else {
                AjaxResult.error("账号属性更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            AjaxResult.error("请求网易云信API失败");
        }
        return AjaxResult.success();
    }
    /**
     * 批量注册
     * @param dto
     * @return
     */
    @Override
    public Result batchRegister(RegisterDto dto) {
        if(dto.getType() == 2){
            return register(dto);
        }else{
            return batchRegister(dto.getNumber());
        }
    }
    /**
     * 同步批量注册
     * 注意:大批量(如超过1000)可能会造成事务过长、数据库连接占用较久,请根据实际情况调整批次大小或考虑异步方式
     * @param count 要注册的账号数量
     * @return 批量注册结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result batchRegister(int count) {
        if (count <= 0) {
            return Result.error("注册数量必须大于0");
        }
        try {
            // 1. 生成批量账号数据
            List<UserAccount> accountsToSave = generateBatchAccounts(count);
            // 2. 批量插入数据库 (使用JDBC Batch,性能远高于MyBatis-Plus的saveBatch)
            batchInsertAccounts(accountsToSave);
            // 3. 批量注册云信账号 (并行处理)
            Result yunxinResult = batchRegisterYunxinAccounts(accountsToSave);
            if (yunxinResult.getCode() != 200) {
                // 云信注册失败,手动触发回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return yunxinResult;
            }
            return Result.success("成功批量注册 " + count + " 个账号");
        } catch (Exception e) {
            // 其他异常,触发回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("批量注册过程发生异常", e);
            return Result.error("批量注册失败: " + e.getMessage());
        }
    }
    /**
     * 生成批量的账号信息
     * @param count 需要生成的数量
     * @return 用户账号列表
     */
    private List<UserAccount> generateBatchAccounts(int count) {
        List<UserAccount> accounts = new ArrayList<>(count);
        Set<String> generatedAccounts = new HashSet<>(count); // 用于内存中去重
        Random random = new Random();
        for (int i = 0; i < count; i++) {
            String account;
            do {
                // 生成13开头的11位随机手机号作为账号
                account = "13" + String.format("%09d", random.nextInt(1000000000));
            } while (generatedAccounts.contains(account)); // 确保本次批量中唯一
            generatedAccounts.add(account);
            UserAccount userAccount = new UserAccount();
            userAccount.setAccount(account);
            userAccount.setPhoneNumber(account);
            userAccount.setCloudMessageAccount(account);
            userAccount.setPassword(ENCRYPTED_PASSWORD); // 使用预加密的密码
            userAccount.setCreateTime(new Date());
            userAccount.setNickname("用户_" + account.substring(7)); // 简单生成昵称
            userAccount.setAccountType(1); // 设置账号类型为1
            accounts.add(userAccount);
        }
        return accounts;
    }
    /**
     * 使用JDBC批量插入数据库,最高效的方式
     * @param accounts 待插入的用户账号列表
     */
    private void batchInsertAccounts(List<UserAccount> accounts) {
        String sql = "INSERT INTO user_account (account, phone_number, cloud_message_account, password, create_time, nickname, account_type) VALUES (?, ?, ?, ?, ?, ?, ?)";
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                UserAccount account = accounts.get(i);
                ps.setString(1, account.getAccount());
                ps.setString(2, account.getPhoneNumber());
                ps.setString(3, account.getCloudMessageAccount());
                ps.setString(4, account.getPassword());
                ps.setTimestamp(5, new java.sql.Timestamp(account.getCreateTime().getTime()));
                ps.setString(6, account.getNickname());
                ps.setInt(7, account.getAccountType());
            }
            @Override
            public int getBatchSize() {
                return accounts.size();
            }
        });
    }
    /**
     * 批量注册云信账号(并行调用单个接口)
     * @param accounts 已存入本地数据库的账号列表
     * @return 注册结果
     */
    private Result batchRegisterYunxinAccounts(List<UserAccount> accounts) {
        // 使用并行流并行调用云信接口
        List<CompletableFuture<YunxinApiResponse>> futures = accounts.parallelStream()
                .map(account -> CompletableFuture.supplyAsync(() -> {
                    Map<String, String> paramMap = new HashMap<>();
                    paramMap.put("accid", account.getAccount());
                    paramMap.put("token", DEFAULT_PASSWORD); // 使用明文密码
                    // 调用云信接口
                    return yunxinClient.executeV1Api(YUNXIN_CREATE_PATH, paramMap);
                }))
                .collect(Collectors.toList());
        // 等待所有异步操作完成,并获取结果
        List<YunxinApiResponse> responses = futures.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());
        // 检查所有响应结果
        for (YunxinApiResponse response : responses) {
            String data = response.getData();
            JSONObject json = JSONObject.parseObject(data);
            int code = json.getIntValue("code");
            if (code != 200) {
                // 记录具体的错误信息
                String errorAccid = json.getString("accid"); // 如果返回了accid
                log.error("云信账号注册失败,accid: {}, 响应: {}, traceId: {}", errorAccid, data, response.getTraceId());
                // 返回第一个遇到的错误
                return Result.error("云信注册失败,错误码: " + code + (errorAccid != null ? ", 账号: " + errorAccid : ""));
            }
        }
        return Result.success("所有云信账号注册成功");
    }
}