From becfbd230bd41688fa7bec25e138e46b49516966 Mon Sep 17 00:00:00 2001 From: luqingjie <544309509@qq.com> Date: Sat, 10 Oct 2026 21:50:24 -0400 Subject: [PATCH] =?UTF-8?q?=E8=87=AA=E5=8A=A8=E8=8E=B7=E5=8F=96=E4=BF=A1?= =?UTF-8?q?=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ruoyi/task/WalletSnapshotRefreshTask.java | 19 ++ .../domain/vo/EnergyAndBandwidthVo.java | 9 + .../system/mapper/WalletAddressMapper.java | 3 + .../service/WalletSnapshotRefreshService.java | 184 ++++++++++++++++++ .../service/impl/TronNileServiceImpl.java | 10 +- .../service/impl/TronProServiceImpl.java | 6 + .../service/impl/TronShastaServiceImpl.java | 6 + .../impl/WalletAddressServiceImpl.java | 75 ++++--- .../mapper/system/WalletAddressMapper.xml | 22 +++ 9 files changed, 292 insertions(+), 42 deletions(-) create mode 100644 ruoyi-admin/src/main/java/com/ruoyi/task/WalletSnapshotRefreshTask.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/service/WalletSnapshotRefreshService.java diff --git a/ruoyi-admin/src/main/java/com/ruoyi/task/WalletSnapshotRefreshTask.java b/ruoyi-admin/src/main/java/com/ruoyi/task/WalletSnapshotRefreshTask.java new file mode 100644 index 0000000..492323f --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/task/WalletSnapshotRefreshTask.java @@ -0,0 +1,19 @@ +package com.ruoyi.task; + +import com.ruoyi.system.service.WalletSnapshotRefreshService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** 定时投递需要刷新的钱包,实际队列和消费逻辑位于 ruoyi-system。 */ +@Component +public class WalletSnapshotRefreshTask { + @Autowired + private WalletSnapshotRefreshService walletSnapshotRefreshService; + + /** 每轮按更新时间投递五个钱包。 */ + @Scheduled(fixedDelayString = "${payment.wallet-snapshot.producer-delay-ms:30000}") + public void produce() { + walletSnapshotRefreshService.enqueueScheduledBatch(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/EnergyAndBandwidthVo.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/EnergyAndBandwidthVo.java index 030d96a..f1cbddc 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/EnergyAndBandwidthVo.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/EnergyAndBandwidthVo.java @@ -19,6 +19,15 @@ public class EnergyAndBandwidthVo implements Serializable { private BigDecimal bandwidth; private BigDecimal energy; + /** 能量总额、已使用量。 */ + private Long energyAllNum; + private Long energyUsedNum; + + /** 质押带宽与免费带宽的总额/可用量。 */ + private Long bandwidthStakedAllNum; + private Long bandwidthFreeNum; + private Long bandwidthFreeAllNum; + private BigDecimal acquiredBandwidth; private BigDecimal acquiredEnergy; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/WalletAddressMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/WalletAddressMapper.java index a138a20..0bb73fd 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/WalletAddressMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/WalletAddressMapper.java @@ -52,6 +52,9 @@ public interface WalletAddressMapper extends BaseMapper WalletAddress selectByAppAndWalletUserName(@Param("appId") Long appId, @Param("walletUserName") String walletUserName); + /** 按最久未刷新优先,查询已分配给支付用户的钱包。 */ + List selectOldestAssignedWallets(@Param("limit") int limit); + /** 仅当钱包仍为空闲状态时绑定归属。 */ int bindAvailableWallet(@Param("id") Long id, @Param("appId") Long appId, @Param("userId") Long userId, @Param("walletUserName") String walletUserName, diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/WalletSnapshotRefreshService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/WalletSnapshotRefreshService.java new file mode 100644 index 0000000..44ba89f --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/WalletSnapshotRefreshService.java @@ -0,0 +1,184 @@ +package com.ruoyi.system.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.domain.WalletAddressPlus; +import com.ruoyi.system.mapper.WalletAddressMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.PriorityBlockingQueue; +import java.util.concurrent.atomic.AtomicLong; + +/** + * 钱包链上快照刷新队列。 + * system 模块中的控制器或业务服务可直接调用 enqueuePriority。 + */ +@Service +public class WalletSnapshotRefreshService { + private static final Logger log = LoggerFactory.getLogger(WalletSnapshotRefreshService.class); + private static final int SCHEDULED_BATCH_SIZE = 5; + private static final int MAX_ATTEMPTS = 3; + private static final int PRIORITY_MANUAL = 0; + private static final int PRIORITY_SCHEDULED = 1; + + private final PriorityBlockingQueue queue = new PriorityBlockingQueue(); + private final ConcurrentHashMap pendingJobs = + new ConcurrentHashMap(); + private final AtomicLong sequence = new AtomicLong(); + private final Object enqueueLock = new Object(); + + @Autowired + private WalletAddressMapper walletAddressMapper; + @Autowired + private IWalletAddressService walletAddressService; + + private volatile boolean running; + private Thread consumerThread; + + @PostConstruct + public void startConsumer() { + running = true; + consumerThread = new Thread(new Runnable() { + @Override + public void run() { + consume(); + } + }, "wallet-snapshot-refresh-consumer"); + consumerThread.setDaemon(true); + consumerThread.start(); + } + + @PreDestroy + public void stopConsumer() { + running = false; + if (consumerThread != null) { + consumerThread.interrupt(); + } + } + + /** 供 ruoyi-admin 定时任务调用,每次投递最久未更新的五个钱包。 */ + public void enqueueScheduledBatch() { + List wallets = walletAddressMapper.selectOldestAssignedWallets(SCHEDULED_BATCH_SIZE); + for (WalletAddressPlus wallet : wallets) { + enqueue(wallet.getToken(), PRIORITY_SCHEDULED); + } + } + + /** + * 将指定钱包地址加入高优先级刷新队列。 + * + * @return 钱包存在并已进入待执行集合(或正在执行)时返回 true + */ + public boolean enqueuePriority(String token) { + if (StringUtils.isBlank(token)) { + return false; + } + String normalizedToken = token.trim(); + WalletAddressPlus wallet = walletAddressService.getOne(new LambdaQueryWrapper() + .select(WalletAddressPlus::getId) + .eq(WalletAddressPlus::getToken, normalizedToken) + .isNull(WalletAddressPlus::getDeletedAt) + .last("limit 1")); + return wallet != null && enqueue(normalizedToken, PRIORITY_MANUAL); + } + + private boolean enqueue(String token, int priority) { + if (StringUtils.isBlank(token)) { + return false; + } + synchronized (enqueueLock) { + WalletRefreshJob existing = pendingJobs.get(token); + if (existing != null) { + // 尚未消费的普通任务可提升优先级;正在执行的任务不能重复投递。 + if (priority < existing.priority && queue.remove(existing)) { + WalletRefreshJob promoted = new WalletRefreshJob(token, priority, sequence.incrementAndGet()); + pendingJobs.put(token, promoted); + queue.offer(promoted); + } + return true; + } + WalletRefreshJob job = new WalletRefreshJob(token, priority, sequence.incrementAndGet()); + pendingJobs.put(token, job); + queue.offer(job); + return true; + } + } + + private void consume() { + while (running) { + WalletRefreshJob job = null; + try { + job = queue.take(); + refreshWithRetry(job.token); + } catch (InterruptedException e) { + if (!running) { + Thread.currentThread().interrupt(); + return; + } + } finally { + if (job != null) { + pendingJobs.remove(job.token, job); + } + } + } + } + + private void refreshWithRetry(String token) { + for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) { + try { + WalletAddressPlus wallet = walletAddressService.getOne( + new LambdaQueryWrapper() + .eq(WalletAddressPlus::getToken, token) + .eq(WalletAddressPlus::getStatus, 1L) + .isNull(WalletAddressPlus::getDeletedAt) + .last("limit 1")); + if (wallet == null) { + return; + } + walletAddressService.updateTronInfo(wallet); + return; + } catch (RuntimeException e) { + if (attempt == MAX_ATTEMPTS) { + log.warn("钱包链上快照连续刷新失败,token={},尝试次数={}", token, MAX_ATTEMPTS); + } else if (!waitBeforeRetry(attempt)) { + return; + } + } + } + } + + private boolean waitBeforeRetry(int attempt) { + try { + Thread.sleep(500L * attempt); + return true; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + + private static final class WalletRefreshJob implements Comparable { + private final String token; + private final int priority; + private final long sequence; + + private WalletRefreshJob(String token, int priority, long sequence) { + this.token = token; + this.priority = priority; + this.sequence = sequence; + } + + @Override + public int compareTo(WalletRefreshJob other) { + int priorityResult = Integer.compare(priority, other.priority); + return priorityResult != 0 ? priorityResult : Long.compare(sequence, other.sequence); + } + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronNileServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronNileServiceImpl.java index d77df2d..512864c 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronNileServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronNileServiceImpl.java @@ -193,6 +193,12 @@ public class TronNileServiceImpl implements ITronService { EnergyAndBandwidthVo result = new EnergyAndBandwidthVo(); result.setBandwidth(BigDecimal.valueOf(bandwidth)); result.setEnergy(BigDecimal.valueOf(energy)); + result.setEnergyAllNum(res.getEnergyLimit()); + result.setEnergyUsedNum(res.getEnergyUsed()); + result.setBandwidthStakedNum(Math.max(0L, res.getNetLimit() - res.getNetUsed())); + result.setBandwidthStakedAllNum(res.getNetLimit()); + result.setBandwidthFreeNum(Math.max(0L, res.getFreeNetLimit() - res.getFreeNetUsed())); + result.setBandwidthFreeAllNum(res.getFreeNetLimit()); return result; } finally { channel.shutdown(); @@ -303,10 +309,6 @@ public class TronNileServiceImpl implements ITronService { int count = delegatedResourceList.getDelegatedResourceCount(); for (int i = 0; i < count; i++) { Response.DelegatedResource delegatedResource = delegatedResourceList.getDelegatedResource(i); - String fromHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getFrom().toByteArray()); - String fromAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(fromHexAddress)); - String toHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getTo().toByteArray()); - String toAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(toHexAddress)); if (resourceCode == 0) { BigDecimal divisor = new BigDecimal("1000000"); BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForBandwidth()).divide(divisor, 4, RoundingMode.HALF_UP); diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronProServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronProServiceImpl.java index 9ee4058..ee7ba31 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronProServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronProServiceImpl.java @@ -234,6 +234,12 @@ public class TronProServiceImpl implements ITronService { EnergyAndBandwidthVo result = new EnergyAndBandwidthVo(); result.setBandwidth(BigDecimal.valueOf(bandwidth)); result.setEnergy(BigDecimal.valueOf(energy)); + result.setEnergyAllNum(res.getEnergyLimit()); + result.setEnergyUsedNum(res.getEnergyUsed()); + result.setBandwidthStakedNum(Math.max(0L, res.getNetLimit() - res.getNetUsed())); + result.setBandwidthStakedAllNum(res.getNetLimit()); + result.setBandwidthFreeNum(Math.max(0L, res.getFreeNetLimit() - res.getFreeNetUsed())); + result.setBandwidthFreeAllNum(res.getFreeNetLimit()); return result; } finally { channel.shutdown(); diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronShastaServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronShastaServiceImpl.java index a6b209e..990ae14 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronShastaServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronShastaServiceImpl.java @@ -273,6 +273,12 @@ public class TronShastaServiceImpl implements ITronService { EnergyAndBandwidthVo result = new EnergyAndBandwidthVo(); result.setBandwidth(BigDecimal.valueOf(bandwidth)); result.setEnergy(BigDecimal.valueOf(energy)); + result.setEnergyAllNum(res.getEnergyLimit()); + result.setEnergyUsedNum(res.getEnergyUsed()); + result.setBandwidthStakedNum(Math.max(0L, res.getNetLimit() - res.getNetUsed())); + result.setBandwidthStakedAllNum(res.getNetLimit()); + result.setBandwidthFreeNum(Math.max(0L, res.getFreeNetLimit() - res.getFreeNetUsed())); + result.setBandwidthFreeAllNum(res.getFreeNetLimit()); return result; } finally { channel.shutdown(); diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/WalletAddressServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/WalletAddressServiceImpl.java index c2eb6e2..25034b3 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/WalletAddressServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/WalletAddressServiceImpl.java @@ -83,49 +83,48 @@ public class WalletAddressServiceImpl extends ServiceImpl + + + + + + + + + + + + + select id, token, status, created_at, updated_at, deleted_at, app_id, user_id, wallet_user_name, token_index, usdt_balance, trx_balance, energy_num, energy_all_num, energy_used_num, bandwidth_num, delegated_energy_trx_num, delegated_energy_value, acquired_delegated_energy_trx_num, acquired_delegated_energy_value, delegated_bandwidth_trx_num, delegated_bandwidth_value, acquired_delegated_bandwidth_trx_num, acquired_delegated_bandwidth_value, staked_trx_num, energy_staked_trx_num, bandwidth_staked_trx_num, vote_num, voted_num, bandwidth_staked_num, bandwidth_staked_all_num, bandwidth_free_num, bandwidth_free_all_num from wallet_address @@ -112,6 +125,15 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" order by id asc limit 1 + + update wallet_address set app_id = #{appId}, user_id = #{userId}, wallet_user_name = #{walletUserName},