關(guān)于nacos,seata-server,seata相關(guān)表等 創(chuàng)建配置請(qǐng)看我前面的文章。
項(xiàng)目結(jié)構(gòu)
|-- demo
|-- entity 實(shí)體對(duì)象(為了讓其他服務(wù)擁有所有服務(wù)對(duì)象)
|-- order 訂單 (pom導(dǎo)入了 entity )
|-- stock 庫(kù)存 (pom導(dǎo)入了 entity )
|-- user 用戶 (pom導(dǎo)入了 entity )

項(xiàng)目依賴(lài)
entity
<properties>
<mybatis-plus>3.3.1.tmp</mybatis-plus>
<db-drive>1.1.23</db-drive>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- 數(shù)據(jù)持久相關(guān)配置 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus}</version>
</dependency>
<!-- 驅(qū)動(dòng) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${db-drive}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- nacos 注冊(cè)中心 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- 多數(shù)據(jù)源,seata分布式事務(wù) -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
</dependencies>
order、stock、user
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>entity</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
<exclusions>
<exclusion>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
</exclusion>
</exclusions>
<version>2.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-all</artifactId>
<version>1.3.0</version>
</dependency>
</dependencies>
配置文件
因?yàn)槔锩嬗衝acos服務(wù)注冊(cè),所以會(huì)有兩個(gè)配置文件,但配置文件基本一樣,所以我就挑user服務(wù)的。
bootstrap.properties
注意 spring.application.name 不同服務(wù)這里是不一樣的
#spring.profiles.active=dev
# Nacos Server 的地址
#spring.cloud.nacos.config.server-addr=0.0.0.0:8848
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
# 這里的對(duì)應(yīng) Nacos Server 中的 Data ID 的前綴
spring.application.name=user-server
# 這里的對(duì)應(yīng) Nacos Server 中的指定的配置規(guī)則格式和 Data ID 的后綴
spring.cloud.nacos.config.file-extension=yaml
# 關(guān)閉動(dòng)態(tài)刷新,默認(rèn)是開(kāi)啟
spring.cloud.nacos.config.refresh.enabled=false
# 服務(wù)發(fā)現(xiàn)
#spring.cloud.nacos.discovery.server-addr=0.0.0.0:8848
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
# 值范圍:1到100。值越大,重量越大。
spring.cloud.nacos.discovery.weight=1
# 集群名稱(chēng)
spring.cloud.nacos.discovery.cluster-name=user
# 心跳間隔 10秒
spring.cloud.nacos.discovery.heart-beat-interval=10000
# sentinel 日志
# spring.cloud.sentinel.log.dir=./sentinel/log
application.yml
以下為多數(shù)據(jù)源配置,但相關(guān)服務(wù)只需要配置相關(guān)庫(kù)就行。
server:
port: 8082
spring:
main:
allow-bean-definition-overriding: true
autoconfigure:
exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
datasource:
druid:
stat-view-servlet:
enabled: true
url-pattern: "/druid/*"
allow: 127.0.0.1
deny: 192.168.1.73
reset-enable: true
login-username: admin
login-password: admin@2020
web-stat-filter:
enabled: true
url-pattern: "/*"
exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
dynamic:
druid:
filters: stat,wall
initial-size: 10
min-idle: 10
maxActive: 200
maxWait: 10000
useUnfairLock: true
validation-query: 'select 1'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
primary: user
# 啟用嚴(yán)格模式
strict: true
seata: true
seata-mode: AT
datasource:
user:
url: jdbc:mysql://0.0.0.0:3306/user?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
username: dev
password: mysql@dev.2020
# 建表腳本
# schema: classpath:db/schema-account.sql
# order:
# url: jdbc:mysql://0.0.0.0:3306/order?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&&serverTimezone=Asia/Shanghai
# driver-class-name: com.mysql.cj.jdbc.Driver
# type: com.alibaba.druid.pool.DruidDataSource
# username: dev
# password: mysql@dev.2020
# stock:
# url: jdbc:mysql://0.0.0.0:3306/stock?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&&serverTimezone=Asia/Shanghai
# driver-class-name: com.mysql.cj.jdbc.Driver
# type: com.alibaba.druid.pool.DruidDataSource
# username: dev
# password: mysql@dev.2020
seata:
enabled: true
# 啟用自動(dòng)代理數(shù)據(jù)源
enable-auto-data-source-proxy: false
# 隨便起個(gè)名字,但最好與服務(wù)名稱(chēng)一致
application-id: ${spring.application.name}
# 此處的名稱(chēng)一定要與 vgroup-mapping下配置的參數(shù)保持一致
tx-service-group: my_test_tx_group
# 目的是找 seata 的配置
config:
type: nacos
nacos:
server-addr: 127.0.0.1:8848
username: nacos
password: nacos@root@2020
namespace:
group: SEATA_GROUP
# registry 目的是找 seata-server 服務(wù)
registry:
type: nacos
nacos:
application: seata-server
server-addr: 127.0.0.1:8848
username: nacos
password: nacos@root@2020
namespace:
代碼
關(guān)于實(shí)體表的結(jié)構(gòu)在上一篇文章已經(jīng)有了,這里直接跳過(guò)。
entity
entity 被所有服務(wù)所引用,所以這里直接寫(xiě) Feign接口是最方便的。
@FeignClient(value = "user-server",path = "/account")
public interface AccountApi {
@PostMapping("/debit")
void debit(@RequestParam("uid") Integer uid, @RequestParam("money") Integer money);
}
@FeignClient(value = "order-server",path = "/order")
public interface OrderApi {
@PostMapping("/create")
void create(@RequestParam("uid") Integer uid,
@RequestParam("stockId") Integer stockId,
@RequestParam("count") Integer count,
@RequestParam("money") Integer money
);
}
@FeignClient(value = "stock-server",path = "/stock")
public interface StockApi {
@PostMapping("/deduct")
Integer deduct(@RequestParam("stockId") Integer stockId, @RequestParam("count") Integer count);
}
order,stock,user
關(guān)于 order,stock,user的mapper 和 server 已經(jīng)在上一篇寫(xiě)過(guò)了,只需要把他們放到對(duì)應(yīng)的服務(wù)里面即可。然后修改實(shí)現(xiàn)類(lèi),把里面調(diào)用其他的server改成調(diào)用 xxxApi即可,在添加一層 controller。以order為例:
@Service
public class OrderServerImpl implements OrderServer {
@Autowired
private OrderMapper orderMapper;
@Autowired
private AccountApi accountApi;
@Override
public void create(Integer uid, Integer stockId, Integer count,Integer money) {
accountApi.debit(uid,money);
Order order = new Order();
order.setUid(uid);
order.setTime(new Date());
order.setCount(count);
order.setMoney(money);
if(1==1){
throw new RuntimeException("下單異常");
}
orderMapper.insert(order);
}
}
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private OrderServer orderServer;
@PostMapping("/create")
public void create(@RequestParam("uid") Integer uid,
@RequestParam("stockId") Integer stockId,
@RequestParam("count") Integer count,
@RequestParam("money") Integer money
){
orderServer.create(uid, stockId, count, money);
}
}
這里我們可以看到 order里面其實(shí)有拋異常的動(dòng)作。
再說(shuō)一遍我們的測(cè)試方案是:
采購(gòu)開(kāi)始 -> 減庫(kù)存,得到所需花費(fèi)金額 -> 用戶減去所需花費(fèi)金額 -> 創(chuàng)建訂單
編寫(xiě)調(diào)用類(lèi)
調(diào)用類(lèi)我是在 user服務(wù)里面做的,方法為 purchase
@RestController
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountServer accountServer;
@Autowired
private BusinessService businessService;
@PostMapping("/debit")
public void debit(@RequestParam("uid") Integer uid, @RequestParam("money") Integer money){
accountServer.debit(uid, money);
}
@PostMapping("/purchase")
public void purchase(@RequestParam("uid") Integer uid,@RequestParam("stockId") Integer stockId ,@RequestParam("count") Integer count){
businessService.purchase(uid, stockId,count);
}
}
再貼一下 BusinessServiceImpl
@Service
public class BusinessServiceImpl implements BusinessService {
@Autowired
private StockApi stockApi;
@Autowired
private OrderApi orderApi;
@GlobalTransactional
@Override
public void purchase(Integer uid, Integer stockId, Integer count) {
Integer money = stockApi.deduct(stockId, count);
orderApi.create(uid, stockId, count,money);
}
}
@GlobalTransactional 全局事務(wù)(分布式事務(wù)注解)
啟動(dòng)所有服務(wù)
服務(wù)全部啟動(dòng)成功之后,你會(huì)在nacos看到如下:

測(cè)試
這里直接測(cè)試下單異常,會(huì)不會(huì)出現(xiàn)訂單沒(méi)創(chuàng)建,但是已經(jīng)扣庫(kù)存和余額。


檢查數(shù)據(jù)庫(kù)數(shù)據(jù):
stock:id=1,num=500,price=5
account:id=1,amount=2000
order:
沒(méi)有進(jìn)行扣除,證明服務(wù)調(diào)用的分布式事務(wù)起作用的。