Skip to content

Commit

Permalink
1.修复积分取消扣减示例代码错误问题。 2.优化部分代码逻辑
Browse files Browse the repository at this point in the history
  • Loading branch information
654894017 committed Feb 20, 2024
1 parent 56a8ee8 commit a4a000e
Show file tree
Hide file tree
Showing 10 changed files with 53 additions and 81 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
# tcc

已解决悬挂、幂等、空回滚问题,业务层面无需关注这部分处理。

# 使用示例

https://github.com/654894017/tcc/tree/master/src/test/java/com/damon/sample

### 步骤1:运行 com.damon.sample.points.PointsApplication

### 步骤2:运行 com.damon.sample.order.TestRun

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ protected void handleException(Exception e) {
try {
tccLogService.update(mainLog);
} catch (Exception exception) {
log.error("业务类型: {}, 业务id :{}, 更新日志重试次数失败", bizType, parameter.getBizId(), e);
log.error("业务类型: {}, 业务id :{}, 更新日志重试次数失败", bizType, parameter.getBizId(), exception);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
package com.damon.tcc.transaction;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.function.Supplier;

public class DefaultLocalTransactionService implements ILocalTransactionService {
private final Logger log = LoggerFactory.getLogger(DefaultLocalTransactionService.class);
@Transactional(rollbackFor = Exception.class)
public <R> R execute(Supplier<R> supplier) {
boolean isTransactionActive = TransactionSynchronizationManager.isActualTransactionActive();
if (!isTransactionActive) {
log.error("spring本地事务不生效,请确认事务配置是否正确");
}
return supplier.get();
}

Expand Down
10 changes: 1 addition & 9 deletions src/test/java/com/damon/sample/order/TestPerformanceRun.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,7 @@ public void test() throws InterruptedException {
@Test
public void testTryFailed() throws InterruptedException {

ExecutorService executorService = Executors.newFixedThreadPool(100);
for (int i = 0; i < 100; i++) {
executorService.submit(() -> {
for (int j = 0; j < 10000; j++) {
orderSubmitAppService.submitOrder(12345679L, 100L);
}
});
}

orderSubmitAppService.submitOrder(12345679L, 100L);

Thread.sleep(20000000);
}
Expand Down
10 changes: 7 additions & 3 deletions src/test/java/com/damon/sample/order/TestRun.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,13 @@ public void test() throws InterruptedException {

@Test
public void testTryFailed() throws InterruptedException {
//不存在的用户id
orderSubmitAppService.submitOrder(12345679L, 100L);
Thread.sleep(2000);
try {
orderSubmitAppService.submitOrder(12345679L, 100L);
Thread.sleep(2000);
} catch (Exception e) {
//需要catch,并睡眠不然线程池来不及调用cancel就被关闭了
Thread.sleep(2000);
}
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ public void executeDeadLogCheck() {

@Override
protected Order callbackParameter(Long bizId) {
Order order = jdbcTemplate.queryForObject("select * from tcc_demo_order where order_id = ? ", new BeanPropertyRowMapper<>(Order.class), bizId);
return order;
return jdbcTemplate.queryForObject("select * from tcc_demo_order where order_id = ? ", new BeanPropertyRowMapper<>(Order.class), bizId);
}

@Override
Expand All @@ -45,12 +44,10 @@ public Long submitOrder(Long userId, Long points) {
Order order = new Order(orderId, 0, userId, points);
return super.process(order);
}

@Override
protected void attempt(Order order) {
pointsGateway.tryDeductionPoints(order.getOrderId(), order.getUserId(), order.getDeductionPoints());
}

@Override
protected Long executeLocalTransaction(Order object) {
int result = jdbcTemplate.update("update tcc_demo_order set status = ? where order_id = ? ", 1, object.getOrderId());
Expand All @@ -59,12 +56,10 @@ protected Long executeLocalTransaction(Order object) {
}
return object.getOrderId();
}

@Override
protected void commit(Order order) {
pointsGateway.commitDeductionPoints(order.getOrderId(), order.getUserId(), order.getDeductionPoints());
}

@Override
protected void cancel(Order order) {
pointsGateway.cancelDeductionPoints(order.getOrderId(), order.getUserId(), order.getDeductionPoints());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,29 +1,46 @@
package com.damon.sample.order.infra.gateway;

import cn.hutool.http.HttpUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.damon.sample.order.domain.IPointsGateway;
import org.springframework.stereotype.Component;

@Component
public class PointsGateway implements IPointsGateway {
@Override
public boolean tryDeductionPoints(Long orderId, Long userId, Long deductionPoints) {

String response = HttpUtil.post("http://localhost:9898/points/try_deduction", "{\"order_id\":" + orderId + ", \"user_id\":" + userId + ", \"deduction_points\":" + deductionPoints + "}", 5000);
HttpResponse httpResponse = HttpRequest.post("http://localhost:9898/points/try_deduction")
.timeout(5000)
.body("{\"order_id\":" + orderId + ", \"user_id\":" + userId + ", \"deduction_points\":" + deductionPoints + "}")
.execute();
if (httpResponse.getStatus() != 200) {
throw new RuntimeException("tryDeductionPoints failed , status : " + httpResponse.body());
}
return true;
}

@Override
public boolean commitDeductionPoints(Long orderId, Long userId, Long deductionPoints) {

String response = HttpUtil.post("http://localhost:9898/points/commit_deduction", "{\"order_id\":" + orderId + ", \"user_id\":" + userId + ", \"deduction_points\":" + deductionPoints + "}", 5000);
HttpResponse httpResponse = HttpRequest.post("http://localhost:9898/points/commit_deduction")
.timeout(5000)
.body("{\"order_id\":" + orderId + ", \"user_id\":" + userId + ", \"deduction_points\":" + deductionPoints + "}")
.execute();
if (httpResponse.getStatus() != 200) {
throw new RuntimeException("commitDeductionPoints failed , status : " + httpResponse.body());
}
return true;
}

@Override
public boolean cancelDeductionPoints(Long orderId, Long userId, Long deductionPoints) {

String response = HttpUtil.post("http://localhost:9898/points/cancel_deduction", "{\"order_id\":" + orderId + ", \"user_id\":" + userId + ", \"deduction_points\":" + deductionPoints + "}", 5000);
HttpResponse httpResponse = HttpRequest.post("http://localhost:9898/points/cancel_deduction")
.timeout(50000)
.body("{\"order_id\":" + orderId + ", \"user_id\":" + userId + ", \"deduction_points\":" + deductionPoints + "}")
.execute();

if (httpResponse.getStatus() != 200) {
throw new RuntimeException("cancelDeductionPoints failed , status : " + httpResponse.body());
}
return true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,16 @@
public class PointsController {
@Autowired
private PointsDeductionAppService pointsDeductionAppService;

@PostMapping("try_deduction")
public Boolean deductionTry(@RequestBody PointsDeductCmd cmd) {
return pointsDeductionAppService.attempt(cmd);
public void deductionTry(@RequestBody PointsDeductCmd cmd) {
pointsDeductionAppService.attempt(cmd);
}

@PostMapping("commit_deduction")
public Boolean deductionCommit(@RequestBody PointsDeductCmd cmd) {
public void deductionCommit(@RequestBody PointsDeductCmd cmd) {
pointsDeductionAppService.commit(cmd);
return true;
}


@PostMapping("cancel_deduction")
public Boolean deductionCancel(@RequestBody PointsDeductCmd cmd) {
public void deductionCancel(@RequestBody PointsDeductCmd cmd) {
pointsDeductionAppService.cancel(cmd);
return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ public PointsDeductionAppService(TccSubConfig config) {
super(config);
this.jdbcTemplate = new JdbcTemplate(config.getDataSource());
}

@Override
public boolean attempt(PointsDeductCmd parameter) {
return super.attempt(parameter, cmd -> {
Expand All @@ -38,6 +37,7 @@ public boolean attempt(PointsDeductCmd parameter) {
return true;
});
}

@Override
public void commit(PointsDeductCmd parameter) {
super.commit(parameter, cmd -> {
Expand All @@ -47,6 +47,7 @@ public void commit(PointsDeductCmd parameter) {
}
});
}

@Override
public void cancel(PointsDeductCmd parameter) {
super.cancel(parameter, cmd -> {
Expand All @@ -56,8 +57,8 @@ public void cancel(PointsDeductCmd parameter) {
return;
}

int result2 = jdbcTemplate.update("update tcc_demo_points set points = points + ? where user_id = ?",
cmd.getUserId(), cmd.getDeductionPoints()
int result2 = jdbcTemplate.update("update tcc_demo_user_points set points = points + ? where user_id = ?",
cmd.getDeductionPoints(), cmd.getUserId()
);
if (result2 == 0) {
throw new RuntimeException("无效的用户id,无法进行积分rollback");
Expand Down

0 comments on commit a4a000e

Please sign in to comment.