package org.example;
import javax.transaction.InvalidTransactionException;
import java.util.UUID;
public class Transaction {
private String id;
private Long buyerId;
private Long createTimestamp;
private int status;
private String walletTransactionId;
// 添加一个成员变量及其 set 方法。就可以将对象放到外面
private WalletRpcService walletRpcService;
private TransactionLock lock;
// 修改点2,提出方法,在test类中重写此方法。
protected boolean isExpired() {
long executionInvokedTimestamp = System.currentTimeMillis();
System.out.println("=======方法内部的isExpired==");
return executionInvokedTimestamp - createTimestamp > 14;
}
public void setTransactionLock(TransactionLock lock) {
this.lock = lock;
}
// 修改点3:WalletRpcService改为注入的方式,通过构造传入,避免在类中new
public Transaction(String preAssignedId, Long buyerId, WalletRpcService walletRpcService) {
if (preAssignedId != null && !preAssignedId.isEmpty()) {
this.id = preAssignedId;
} else {
this.id = UUID.randomUUID().toString();
}
if (!this.id.startsWith("t_")) {
this.id = "t_" + preAssignedId;
}
this.buyerId = buyerId;
this.status = STATUS.TO_BE_EXECUTD;
this.createTimestamp = System.currentTimeMillis();
this.walletRpcService = walletRpcService;
}
public boolean execute() throws InvalidTransactionException {
if (buyerId == null) {
throw new InvalidTransactionException();
}
if (status == STATUS.EXECUTED) {
return true;
}
boolean isLocked = false;
try {
isLocked = lock.lock(id);
if (!isLocked) {
return false; // 锁定未成功,返回 false,job 兜底执行
}
if (status == STATUS.EXECUTED) {
return true;
}
// createTimestamp 临时
if (isExpired()) {
this.status = STATUS.EXPIRED;
return false;
}
String walletTransactionId = walletRpcService.moveMoney();
if (walletTransactionId != null) {
this.walletTransactionId = walletTransactionId;
this.status = STATUS.EXECUTED;
return true;
} else {
this.status = STATUS.FAILED;
return false;
}
} finally {
if (isLocked) {
lock.unlock(id);
}
}
}
}
没有合适的资源?快使用搜索试试~ 我知道了~
资源详情
资源评论
资源推荐
收起资源包目录
test code.zip (10个子文件)
修改后可测试程序(含单元测试用例)
Transaction.java 3KB
TransactionLock.java 311B
WalletRpcService.java 196B
STATUS.java 204B
RedisDistributedLock.java 323B
TransactionTest.java 2KB
MockWalletRpcServiceOne.java 240B
不可测试程序
Transaction.java 3KB
WalletRpcService.java 201B
STATUS.java 209B
共 10 条
- 1
zhaoronghui1314
- 粉丝: 825
- 资源: 8
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论0