Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TAC模式下,实现读已提交的隔离级别,并在 hmily-demo-tac-dubbo 模块增加对应测试案例 #356

Merged
merged 3 commits into from
Jul 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -85,5 +85,6 @@ public interface AccountService {
* @param userId 用户id
* @return AccountDO account do
*/
@Hmily
AccountDO findByUserId(String userId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,8 @@ public boolean paymentWithNestedException(final AccountNestedDTO accountNestedDT
inventoryService.mockWithTryException(inventoryDTO);
return Boolean.TRUE;
}


@HmilyTAC
@Override
public AccountDO findByUserId(final String userId) {
return accountMapper.findByUserId(userId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,14 @@ public String mockInventoryWithConfirmTimeout(final @RequestParam(value = "count
final @RequestParam(value = "amount") BigDecimal amount) {
return orderService.mockInventoryWithConfirmTimeout(count, amount);
}

@PostMapping(value = "/mockReadCommitted")
@ApiOperation(value = "订单支付接口(模拟读已提交的隔离级别)")
public String mockOrderPayWithReadCommitted(final @RequestParam(value = "count") Integer count,
final @RequestParam(value = "amount") BigDecimal amount) {
final long start = System.currentTimeMillis();
orderService.orderPayWithReadCommitted(count, amount);
System.out.println("消耗时间为:" + (System.currentTimeMillis() - start));
return "";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -117,4 +117,12 @@ public interface OrderService {
* @return true or false
*/
boolean updateOrderStatus(Order order);

/**
* 订单支付接口(模拟读已提交的隔离级别)
* @param count 购买数量
* @param amount 支付金额
* @return string string
*/
String orderPayWithReadCommitted(Integer count, BigDecimal amount);
}
Original file line number Diff line number Diff line change
Expand Up @@ -93,4 +93,11 @@ public interface PaymentService {
* @return String string
*/
String mockPaymentInventoryWithConfirmTimeout(Order order);

/**
* 订单支付.
*
* @param order 订单实体
*/
String makePaymentWithReadCommitted(Order order);
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package org.dromara.hmily.demo.tac.dubbo.order.service.impl;

import org.dromara.hmily.common.utils.IdWorkerUtils;
import org.dromara.hmily.demo.common.account.api.AccountService;
import org.dromara.hmily.demo.common.order.entity.Order;
import org.dromara.hmily.demo.common.order.enums.OrderStatusEnum;
import org.dromara.hmily.demo.common.order.mapper.OrderMapper;
Expand Down Expand Up @@ -46,8 +47,8 @@ public class OrderServiceImpl implements OrderService {
private final PaymentService paymentService;

@Autowired(required = false)
public OrderServiceImpl(OrderMapper orderMapper,
PaymentService paymentService) {
public OrderServiceImpl(final OrderMapper orderMapper,
final PaymentService paymentService) {
this.orderMapper = orderMapper;
this.paymentService = paymentService;
}
Expand Down Expand Up @@ -153,12 +154,21 @@ public String mockInventoryWithConfirmTimeout(Integer count, BigDecimal amount)
public boolean updateOrderStatus(Order order) {
return orderMapper.update(order) > 0;
}

private Order saveOrder(Integer count, BigDecimal amount) {
final Order order = buildOrder(count, amount);
orderMapper.save(order);
return order;
}

@Override
public String orderPayWithReadCommitted(Integer count, BigDecimal amount) {
Order order = saveOrder(count, amount);
long start = System.currentTimeMillis();
paymentService.makePaymentWithReadCommitted(order);
System.out.println("切面耗时:" + (System.currentTimeMillis() - start));
return "success";
}

private Order buildOrder(Integer count, BigDecimal amount) {
Order order = new Order();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,20 @@ public String mockPaymentInventoryWithConfirmTimeout(final Order order) {
inventoryService.mockWithConfirmTimeout(buildInventoryDTO(order));
return "success";
}


@Override
@HmilyTAC
public String makePaymentWithReadCommitted(Order order) {
updateOrderStatus(order, OrderStatusEnum.PAY_SUCCESS);
//扣除用户余额
accountService.payment(buildAccountDTO(order));
//查询账户信息, 读已提交, 此时该事务未结束, 获取全局锁失败, 将会回滚
accountService.findByUserId(order.getUserId());
//进入扣减库存操作
inventoryService.decrease(buildInventoryDTO(order));
return "success";
}

private void updateOrderStatus(final Order order, final OrderStatusEnum orderStatus) {
order.setStatus(orderStatus.getCode());
orderMapper.update(order);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,5 @@
*/
public enum HmilySQLManipulation {

INSERT, DELETE, UPDATE
INSERT, DELETE, UPDATE, SELECT
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import org.dromara.hmily.tac.sqlcompute.HmilySQLComputeEngine;
import org.dromara.hmily.tac.sqlcompute.HmilySQLComputeEngineFactory;
import org.dromara.hmily.tac.sqlparser.model.common.statement.HmilyStatement;
import org.dromara.hmily.tac.sqlparser.model.common.statement.dml.HmilySelectStatement;
import org.dromara.hmily.tac.sqlparser.spi.HmilySqlParserEngineFactory;

import java.sql.Connection;
Expand Down Expand Up @@ -104,7 +105,9 @@ public void execute(final String sql, final List<Object> parameters, final Conne
HmilyUndoContext undoContext = buildUndoContext(HmilyContextHolder.get(), snapshot, resourceId);
HmilyLockManager.INSTANCE.tryAcquireLocks(undoContext.getHmilyLocks());
log.debug("TAC-try-lock ::: {}", undoContext.getHmilyLocks());
HmilyUndoContextCacheManager.INSTANCE.set(undoContext);
if (!(statement instanceof HmilySelectStatement)) {
HmilyUndoContextCacheManager.INSTANCE.set(undoContext);
}
}

private HmilyUndoContext buildUndoContext(final HmilyTransactionContext transactionContext, final HmilyDataSnapshot dataSnapshot, final String resourceId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
* @author zhaojun
*/
public interface HmilySQLComputeEngine {

/**
* Generate snapshot images.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@
import org.dromara.hmily.tac.sqlcompute.exception.SQLComputeException;
import org.dromara.hmily.tac.sqlcompute.impl.HmilyDeleteSQLComputeEngine;
import org.dromara.hmily.tac.sqlcompute.impl.HmilyInsertSQLComputeEngine;
import org.dromara.hmily.tac.sqlcompute.impl.HmilySelectSQLComputeEngine;
import org.dromara.hmily.tac.sqlcompute.impl.HmilyUpdateSQLComputeEngine;
import org.dromara.hmily.tac.sqlparser.model.common.statement.HmilyStatement;
import org.dromara.hmily.tac.sqlparser.model.dialect.mysql.dml.HmilyMySQLDeleteStatement;
import org.dromara.hmily.tac.sqlparser.model.dialect.mysql.dml.HmilyMySQLInsertStatement;
import org.dromara.hmily.tac.sqlparser.model.dialect.mysql.dml.HmilyMySQLSelectStatement;
import org.dromara.hmily.tac.sqlparser.model.dialect.mysql.dml.HmilyMySQLUpdateStatement;

/**
Expand All @@ -31,7 +33,7 @@
* @author zhaojun
*/
public final class HmilySQLComputeEngineFactory {

/**
* Create new instance of hmily SQL compute engine.
*
Expand All @@ -46,6 +48,8 @@ public static HmilySQLComputeEngine newInstance(final HmilyStatement hmilyStatem
return new HmilyUpdateSQLComputeEngine((HmilyMySQLUpdateStatement) hmilyStatement);
} else if (hmilyStatement instanceof HmilyMySQLDeleteStatement) {
return new HmilyDeleteSQLComputeEngine((HmilyMySQLDeleteStatement) hmilyStatement);
} else if (hmilyStatement instanceof HmilyMySQLSelectStatement) {
return new HmilySelectSQLComputeEngine((HmilyMySQLSelectStatement) hmilyStatement);
} else {
throw new SQLComputeException(String.format("do not support hmily SQL compute yet, SQLStatement:{%s}.", hmilyStatement));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
* @author zhaojun
*/
public class HmilySQLComputeUtils {

/**
* Execute query.
*
Expand Down Expand Up @@ -65,11 +65,11 @@ public static Collection<Map<String, Object>> executeQuery(final Connection conn
}
return result;
}

/**
* Get all columns.
*
* @param segment hmily simple table segment
* @param segment hmily simple table segment
* @param tableName table name
* @return all table columns in asterisk way
*/
Expand All @@ -84,4 +84,31 @@ public static String getAllColumns(final HmilySimpleTableSegment segment, final
}
return result;
}

/**
* Get all pk columns.
*
* @param segment hmily simple table segment
* @param tableName table name
* @param primaryKeyColumns primary key columns
* @return all table primary key columns in asterisk way
*/
public static String getAllPKColumns(final HmilySimpleTableSegment segment, final String tableName, final List<String> primaryKeyColumns) {
StringBuilder pkNamesStr = new StringBuilder();
for (int i = 0; i < primaryKeyColumns.size(); i++) {
if (i > 0) {
pkNamesStr.append(" , ");
}
String pkName = null;
if (segment.getAlias().isPresent()) {
pkName = String.format("%s.%s", segment.getAlias().get(), primaryKeyColumns.get(i));
} else if (segment.getOwner().isPresent()) {
pkName = String.format("%s.%s.%s", segment.getOwner(), tableName, primaryKeyColumns.get(i));
} else {
pkName = String.format("%s.%s", tableName, primaryKeyColumns.get(i));
}
pkNamesStr.append(pkName);
}
return pkNamesStr.toString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package org.dromara.hmily.tac.sqlcompute.impl;

import lombok.RequiredArgsConstructor;
import org.dromara.hmily.repository.spi.entity.tuple.HmilySQLManipulation;
import org.dromara.hmily.repository.spi.entity.tuple.HmilySQLTuple;
import org.dromara.hmily.tac.metadata.HmilyMetaDataManager;
import org.dromara.hmily.tac.metadata.model.TableMetaData;
import org.dromara.hmily.tac.sqlparser.model.common.segment.dml.order.HmilyOrderBySegment;
import org.dromara.hmily.tac.sqlparser.model.common.segment.dml.pagination.limit.HmilyLimitSegment;
import org.dromara.hmily.tac.sqlparser.model.common.segment.generic.table.HmilySimpleTableSegment;
import org.dromara.hmily.tac.sqlparser.model.dialect.mysql.dml.HmilyMySQLSelectStatement;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* Hmily select SQL compute engine.
*
* @author zhangzhi
*/
@RequiredArgsConstructor
public class HmilySelectSQLComputeEngine extends AbstractHmilySQLComputeEngine {

private final HmilyMySQLSelectStatement sqlStatement;

@Override
Collection<HmilySQLTuple> createTuples(final String sql, final List<Object> parameters, final Connection connection, final String resourceId) throws SQLException {
Collection<HmilySQLTuple> result = new LinkedList<>();
HmilySimpleTableSegment tableSegment = (HmilySimpleTableSegment) sqlStatement.getTableSegment();
String tableName = tableSegment.getTableName().getIdentifier().getValue();
List<String> primaryKeyColumns = HmilyMetaDataManager.get(resourceId).getTableMetaDataMap().get(tableName).getPrimaryKeyColumns();
String selectPKSQL = String.format("SELECT %s FROM %s %s %s %s", HmilySQLComputeUtils.getAllPKColumns(tableSegment, tableName, primaryKeyColumns), tableName,
getWhereCondition(sql), getOrderByCondition(sql), getLimitCondition(sql));
Collection<Map<String, Object>> records = HmilySQLComputeUtils.executeQuery(connection, selectPKSQL, parameters);
result.addAll(doConvert(records, HmilyMetaDataManager.get(resourceId).getTableMetaDataMap().get(tableName)));
return result;
}

private String getWhereCondition(final String sql) {
return sqlStatement.getWhere().map(segment -> sql.substring(segment.getStartIndex(), segment.getStopIndex() + 1)).orElse("");
}

private String getOrderByCondition(final String sql) {
HmilyOrderBySegment orderBy = sqlStatement.getOrderBy();
if (orderBy != null) {
return sql.substring(orderBy.getStartIndex(), orderBy.getStopIndex() + 1);
}
return "";
}

private String getLimitCondition(final String sql) {
if (sqlStatement.getLimit().isPresent()) {
HmilyLimitSegment limitSegment = sqlStatement.getLimit().get();
return sql.substring(limitSegment.getStartIndex(), limitSegment.getStopIndex() + 1);
}
return "";
}

private Collection<HmilySQLTuple> doConvert(final Collection<Map<String, Object>> records, final TableMetaData tableMetaData) {
Collection<HmilySQLTuple> result = new LinkedList<>();
for (Map<String, Object> record : records) {
List<Object> primaryKeyValues = tableMetaData.getPrimaryKeyColumns().stream().map(record::get).collect(Collectors.toList());
result.add(buildTuple(tableMetaData.getTableName(), HmilySQLManipulation.SELECT, primaryKeyValues, new LinkedHashMap<>(), new LinkedHashMap<>()));
}
return result;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.dromara.hmily.tac.sqlparser.model.common.constant.HmilyOrderDirection;
import org.dromara.hmily.tac.sqlparser.model.common.segment.HmilySegment;

Expand All @@ -26,6 +27,7 @@
*/
@RequiredArgsConstructor
@Getter
@Setter
public abstract class HmilyOrderByItemSegment implements HmilySegment {

private final int startIndex;
Expand All @@ -35,4 +37,5 @@ public abstract class HmilyOrderByItemSegment implements HmilySegment {
private final HmilyOrderDirection hmilyOrderDirection;

private final HmilyOrderDirection nullHmilyOrderDirection;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package org.dromara.hmily.tac.sqlparser.model.common.statement.dml;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.dromara.hmily.tac.sqlparser.model.common.segment.dml.order.HmilyOrderBySegment;
import org.dromara.hmily.tac.sqlparser.model.common.segment.dml.predicate.HmilyWhereSegment;
import org.dromara.hmily.tac.sqlparser.model.common.segment.generic.table.HmilyTableSegment;
import org.dromara.hmily.tac.sqlparser.model.common.statement.AbstractHmilyStatement;

import java.util.Optional;

/**
* select statement.
*
* @author zhangzhi
*/
@Getter
@Setter
@ToString
public abstract class HmilySelectStatement extends AbstractHmilyStatement implements HmilyDMLStatement {

private HmilyTableSegment tableSegment;

private HmilyWhereSegment where;

private HmilyOrderBySegment orderBy;

/**
* Get where.
*
* @return where segment
*/
public Optional<HmilyWhereSegment> getWhere() {
return Optional.ofNullable(where);
}

/**
* Get orderBy.
*
* @return orderBy segment
*/
public Optional<HmilyOrderBySegment> gteOrderBy() {
return Optional.ofNullable(orderBy);
}
}
Loading