本文主要內(nèi)容為seata的實(shí)踐篇毕莱,理論知識不懂的請參考前文:
主要介紹兩種最常用的TCC和AT模式器贩。
環(huán)境信息:
mysql:5.7.32
seata-server:1.4.1
SpringCloud:Hoxton.SR10
SpringBoot:2.3.8.RELEASE
注冊中心:Eureka
涉及服務(wù):
Seata-server
1、在file.conf中修改
mode = "db"
然后配置DB信息:
## database store property
db {
datasource = "druid"
## mysql/oracle/postgresql/h2/oceanbase etc.
dbType = "mysql"
driverClassName = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://127.0.0.1:3306/seata"
user = "root"
password = "123456"
minConn = 5
maxConn = 100
globalTable = "global_table"
branchTable = "branch_table"
lockTable = "lock_table"
queryLimit = 100
maxWait = 5000
}
2朋截、在register.conf
registry {
# file 蛹稍、nacos 、eureka质和、redis稳摄、zk稚字、consul饲宿、etcd3厦酬、sofa
type = "eureka"
loadBalance = "RandomLoadBalance"
loadBalanceVirtualNodes = 10
eureka {
serviceUrl = "http://eureka-chengdu:8761/eureka,http://eureka-hangzhou:8762/eureka"
application = "seata-server"
weight = "1"
}
3、客戶端修改
這里所指的客戶端包含所有的資源管理器瘫想,包含所有需要seata-server管理的服務(wù)
在服務(wù)啟動yml中增加:
seata:
enabled: true
# 事務(wù)群組(可以每個應(yīng)用獨(dú)立取名仗阅,也可以使用相同的名字)
tx-service-group: my_tx_group
client:
rm-report-success-enable: true
# 異步提交緩存隊(duì)列長度(默認(rèn)10000)
rm-async-commit-buffer-limit: 1000
# 一階段全局提交結(jié)果上報TC重試次數(shù)(默認(rèn)1次,建議大于1)
tm-commit-retry-count: 3
# 一階段全局回滾結(jié)果上報TC重試次數(shù)(默認(rèn)1次国夜,建議大于1)
tm-rollback-retry-count: 3
support:
# 數(shù)據(jù)源自動代理開關(guān)(默認(rèn)false關(guān)閉)
spring-datasource-autoproxy: false
service:
vgroup-mapping:
# TC 集群(必須與seata-server保持一致)
my_tx_group: seata-server
grouplist:
default: seata-server:8091
registry:
type: eureka
eureka:
serviceUrl: http://eureka-chengdu:8761/eureka/,http://eureka-hangzhou:8762/eureka/
TCC模式
TCC模式實(shí)踐需要四個服務(wù)减噪,除了seata-server外,其他服務(wù)調(diào)用關(guān)系如下:
business服務(wù)是全局事務(wù)的發(fā)起者车吹,需要增加@GlobalTransactional注解
@Override
@GlobalTransactional
public String processTcc(Map<String, String> params) {
String xid = RootContext.getXID();
System.out.println(("---》》》》xid:" + xid));
uploadFeign.upload(params);
downloadFeign.download(params);
return xid;
}
business服務(wù)會通過feign遠(yuǎn)程調(diào)用upload和download服務(wù)筹裕,這兩個服務(wù)都要聲明TCC的三個接口,并通過TwoPhaseBusinessAction注解聲明窄驹。
upload服務(wù):
@LocalTCC
public interface TccService {
@TwoPhaseBusinessAction(name = "upload", commitMethod = "commitTcc", rollbackMethod = "cancel")
String upload(@BusinessActionContextParameter(paramName = "params") Map<String, String> params);
boolean commitTcc(BusinessActionContext context);
boolean cancel(BusinessActionContext context);
}
具體實(shí)現(xiàn)朝卒,這里模擬了TCC結(jié)果并放到Result中,通過restful接口可以查看乐埠,實(shí)際業(yè)務(wù)需要考慮防懸掛和空回滾問題抗斤,例子只是簡單描述如何使用TCC模式:
@Slf4j
@Service
public class TccServiceImpl implements TccService {
@Value("${spring.application.name}")
private String appName;
@PostConstruct
private void initAppName() {
Result.getResult().setAppName(appName);
}
@Override
public String upload(Map<String, String> params) {
String xid = RootContext.getXID();
System.out.println(("---》》》》xid: " + xid));
return "success";
}
@Override
public boolean commitTcc(BusinessActionContext context) {
String xbid = context.getXid();
System.out.println(("---》》》》xid: " + xbid + "提交成功"));
Result.getResult().setActionResult(context.getXid(), +context.getBranchId(), "Commit", context.getActionContext("params"));
return true;
}
@Override
public boolean cancel(BusinessActionContext context) {
System.out.println(("---》》》》xid: " + context.getXid() + "回滾成功"));
Result.getResult().setActionResult(context.getXid(), context.getBranchId(), "Rollback", context.getActionContext("params"));
return true;
}
}
download服務(wù)
download服務(wù)也同樣需要聲明一個TCC接口,實(shí)現(xiàn)上在Try階段模擬每三次調(diào)用,丈咐,延遲30s失敗一次場景
@Override
public String download(Map<String, String> params) {
String xid = RootContext.getXID();
System.out.println(("---》》》》xid: " + xid));
if (count.incrementAndGet() % 3 == 0) {
try {
TimeUnit.SECONDS.sleep(30);
} catch (InterruptedException e) {
log.warn("InterruptedException", e);
}
throw new RuntimeException("服務(wù)異常");
}
return "success";
}
測試
1瑞眼、通過restful接口調(diào)用兩次,返回全局事務(wù)ID
2棵逊、查看download和upload服務(wù)結(jié)果伤疙,可以看到結(jié)果都是成功。
upload結(jié)果:
3辆影、通過日志查看
seata-server:
business服務(wù)日志:
第三次調(diào)用
第三次模擬的是download服務(wù)失敗場景掩浙,所以能看到download結(jié)果是失敗回滾
但是upload服務(wù)并沒有異常,來看下是否能夠和download保證事務(wù)的一致性秸歧,結(jié)果都是回滾呢厨姚?
從結(jié)果看到兩個服務(wù)結(jié)果是相同的,從而也看出保證了事務(wù)一致性键菱。
從seata-server日志也能看到回滾成功的信息:
AT模式
AT模式實(shí)踐需要四個服務(wù)谬墙,除了seata-server外,其他服務(wù)調(diào)用關(guān)系如下:
模擬電商場景经备,下訂單拭抬、減庫存,處理成功后侵蒙,第三次調(diào)用時延時30s拋出異常
業(yè)務(wù)觸發(fā)測造虎,也就是全局事務(wù)發(fā)起服務(wù)business服務(wù):
@Override
@GlobalTransactional(rollbackFor = Exception.class)
public String processAt(String userId, int orderMoney, String commodityCode, int count) throws InterruptedException {
String xid = RootContext.getXID();
System.out.println("---》》》》xid:" + xid);
System.out.println(("------->創(chuàng)建訂單開始"));
orderFeign.create(userId, commodityCode, count, orderMoney);
System.out.println(("------->創(chuàng)建訂單結(jié)束"));
System.out.println(("------->扣減庫存開始"));
storageFeign.deduct(commodityCode, count);
System.out.println(("------->扣減庫存結(jié)束"));
if (visitCount.incrementAndGet() % 3 == 0) {
TimeUnit.SECONDS.sleep(30);
throw new RuntimeException("process failed");
}
return xid;
}
order服務(wù)、storage服務(wù)
除了配置中增加seata外纷闺,與普通的入庫服務(wù)是一樣的
@Service
public class OrderDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public boolean createOrder(Order order) {
String sql = "INSERT INTO product_order (user_id,product_id,count,money,status) VALUES('" + order.getUserId() + "', " + order.getProductId() + "," + order.getCount() + ", " + order.getMoney() + ",0);";
return jdbcTemplate.update(sql) > 0;
}
}
調(diào)用之前:數(shù)據(jù):
order數(shù)據(jù)庫為空算凿,
storage數(shù)據(jù)庫中庫存字段為100:
調(diào)用兩次后:
數(shù)據(jù)庫結(jié)果:
第三次調(diào)用是模擬延時30s后失敗場景份蝴,也就是書庫更新后,處理數(shù)據(jù)失敗氓轰,應(yīng)該從數(shù)據(jù)庫看到數(shù)據(jù)回滾過程婚夫,延遲30s也是為了更好的觀察結(jié)果,也可以用debug方式觀察結(jié)果
也可以看到
rollback_info中:
30s后重新查詢書庫可以看到storage庫存變回98署鸡,order記錄減少為2條案糙,同時undo_log和seata相關(guān)表中數(shù)據(jù)被清空。
從seata-server日志也能看到回滾信息靴庆。
華為
同時看下華為的分布式事務(wù)解決方案时捌,相比于seata直觀的就是多了交互命令行,從上面例子也可以看出seata目前還只能通過數(shù)據(jù)庫查看結(jié)果
其他和seata類似提供了TCC和非侵入兩種方案
seata-golang
參考容器時代:seata-golang 接入指南
總結(jié)
例子中涉及的代碼已上傳到github
https://github.com/stevenniu9527/nerry
如果有時間還是建議自己敲一遍代碼炉抒,看別人的東西都會覺得很簡單匣椰,一看就會
但是當(dāng)自己實(shí)操時就會發(fā)現(xiàn)各種奇奇怪怪的異常,一用就廢端礼。
紙上得來終覺淺禽笑,絕知此事要躬行,
比如例子中子pom依賴為什么不需要配置版本蛤奥、eureka兩個怎么互為副本的佳镜、seata相關(guān)表中具體數(shù)據(jù)是什么、debug和延遲30s是否會對seata有影響
這些問題自己敲一遍會有更深的理解凡桥,更何況代碼量是如此的少蟀伸。
最后覺得寫的還行,求關(guān)注缅刽,求點(diǎn)贊啊掏,求轉(zhuǎn)發(fā)