1.3.5.3、实现类
@Service public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService { @Override @Transactional public UserInfo saveUserInfo(UserInfo userInfo) { userInfo.setId(IdUtils.getId()); this.save(userInfo); return userInfo; } @Override public UserInfo getUserInfoById(Long id) { return this.getById(id); } @Override public List<UserInfo> listUserInfo() { QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>(); userInfoQueryWrapper.between("id",1623695688380448768L,1623695688380448769L); return this.list(userInfoQueryWrapper); } }
1.3.6、生成ID - 雪花算法
package com.xxxx.tore.common.utils; import cn.hutool.core.lang.Snowflake; import cn.hutool.core.util.IdUtil; /** * 生成各种组件ID */ public class IdUtils { /** * 雪花算法 * @return */ public static long getId(){ Snowflake snowflake = IdUtil.getSnowflake(0, 0); long id = snowflake.nextId(); return id; } }
1.4、seata与sharding-jdbc整合
1.4.1、common中添加依赖
<!--seata依赖--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-seata</artifactId> <version>2021.0.4.0</version> </dependency> <!-- sharding-jdbc整合seata分布式事务--> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>sharding-transaction-base-seata-at</artifactId> <version>4.1.1</version> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <version>2021.0.4.0</version> <exclusions> <exclusion> <groupId>com.alibaba.nacos</groupId> <artifactId>nacos-client</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.alibaba.nacos</groupId> <artifactId>nacos-client</artifactId> <version>1.4.2</version> </dependency>
1.4.2、改造account-service服务
@Service public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService { @Autowired private OrderService orderService; @Autowired private StorageService storageService; /** * 存放商品编码及其对应的价钱 */ private static Map<String,Integer> map = new HashMap<>(); static { map.put("c001",3); map.put("c002",5); map.put("c003",10); map.put("c004",6); } @Override @Transactional @ShardingTransactionType(TransactionType.BASE) public void debit(OrderDTO orderDTO) { //扣减账户余额 int calculate = this.calculate(orderDTO.getCommodityCode(), orderDTO.getCount()); AccountDTO accountDTO = new AccountDTO(orderDTO.getUserId(), calculate); QueryWrapper<Account> objectQueryWrapper = new QueryWrapper<>(); objectQueryWrapper.eq("id",1); objectQueryWrapper.eq(accountDTO.getUserId() != null,"user_id",accountDTO.getUserId()); Account account = this.getOne(objectQueryWrapper); account.setMoney(account.getMoney() - accountDTO.getMoney()); this.saveOrUpdate(account); //扣减库存 this.storageService.deduct(new StorageDTO(null,orderDTO.getCommodityCode(),orderDTO.getCount())); //生成订单 this.orderService.create(orderDTO); } /** * 计算购买商品的总价钱 * @param commodityCode * @param orderCount * @return */ private int calculate(String commodityCode, int orderCount){ //商品价钱 Integer price = map.get(commodityCode) == null ? 0 : map.get(commodityCode); return price * orderCount; } }
注意:调单生成调用的逻辑修改,减余额->减库存->生成订单。调用入口方法注解加上:@ShardingTransactionType(TransactionType.BASE)
1.4.3、修改business-service服务
@Service public class BusinessServiceImpl implements BusinessService { @Autowired private OrderService orderService; @Autowired private StorageService storageService; @Autowired private AccountService accountService; @Override public void purchase(OrderDTO orderDTO) { //扣减账号中的钱 accountService.debit(orderDTO); } }
1.4.4、修改order-service服务
@Service public class OrderServiceImpl extends ServiceImpl<OrderMapper,Order> implements OrderService { /** * 存放商品编码及其对应的价钱 */ private static Map<String,Integer> map = new HashMap<>(); static { map.put("c001",3); map.put("c002",5); map.put("c003",10); map.put("c004",6); } @Override @Transactional @ShardingTransactionType(TransactionType.BASE) public Order create(String userId, String commodityCode, int orderCount) { int orderMoney = calculate(commodityCode, orderCount); Order order = new Order(); order.setUserId(userId); order.setCommodityCode(commodityCode); order.setCount(orderCount); order.setMoney(orderMoney); //保存订单 this.save(order); try { TimeUnit.SECONDS.sleep(30); } catch (InterruptedException e) { e.printStackTrace(); } if(true){ throw new RuntimeException("回滚测试"); } return order; } /** * 计算购买商品的总价钱 * @param commodityCode * @param orderCount * @return */ private int calculate(String commodityCode, int orderCount){ //商品价钱 Integer price = map.get(commodityCode) == null ? 0 : map.get(commodityCode); return price * orderCount; } }
1.4.5、配置文件参考
server: port: 8090 spring: main: # 一个实体类对应多张表,覆盖 allow-bean-definition-overriding: true shardingsphere: datasource: ds0: #配置数据源具体内容,包含连接池,驱动,地址,用户名和密码 driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: jdbc:mysql://127.0.0.1:3306/account?autoReconnect=true&allowMultiQueries=true password: root type: com.zaxxer.hikari.HikariDataSource username: root ds1: driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: jdbc:mysql://127.0.0.1:3306/account?autoReconnect=true&allowMultiQueries=true password: root type: com.zaxxer.hikari.HikariDataSource username: root # 配置数据源,给数据源起名称 names: ds0,ds1 props: sql: show: true sharding: tables: account_tbl: actual-data-nodes: ds0.account_tbl_${0..1} database-strategy: standard: preciseAlgorithmClassName: com.xxxx.store.account.config.PreciseDBExtShardingAlgorithm #rangeAlgorithmClassName: com.xxxx.store.account.config.RangeDBShardingAlgorithm sharding-column: id table-strategy: standard: preciseAlgorithmClassName: com.xxxx.store.account.config.PreciseTablesExtShardingAlgorithm #rangeAlgorithmClassName: com.xxxx.store.account.config.RangeTablesShardingAlgorithm sharding-column: id user_info: #指定 user_info 表分布情况,配置表在哪个数据库里面,表名称都是什么 actual-data-nodes: ds0.user_info_${0..9} database-strategy: standard: preciseAlgorithmClassName: com.xxxx.store.account.config.PreciseDBShardingAlgorithm rangeAlgorithmClassName: com.xxxx.store.account.config.RangeDBShardingAlgorithm sharding-column: id table-strategy: standard: preciseAlgorithmClassName: com.xxxx.store.account.config.PreciseTablesShardingAlgorithm rangeAlgorithmClassName: com.xxxx.store.account.config.RangeTablesShardingAlgorithm sharding-column: id #以上是sharding-jdbc配置 cloud: nacos: discovery: server-addr: localhost:8848 namespace: 1ff3782d-b62d-402f-8bc4-ebcf40254d0a application: name: account-service #微服务名称 # datasource: # username: root # password: root # url: jdbc:mysql://127.0.0.1:3306/account # driver-class-name: com.mysql.cj.jdbc.Driver seata: enabled: true enable-auto-data-source-proxy: false application-id: account-service tx-service-group: default_tx_group service: vgroup-mapping: default_tx_group: default disable-global-transaction: false registry: type: nacos nacos: application: seata-server server-addr: 127.0.0.1:8848 namespace: 1ff3782d-b62d-402f-8bc4-ebcf40254d0a group: SEATA_GROUP username: nacos password: nacos config: nacos: server-addr: 127.0.0.1:8848 namespace: 1ff3782d-b62d-402f-8bc4-ebcf40254d0a group: SEATA_GROUP username: nacos password: nacos