南通快速建站公司公司建網(wǎng)站多少錢
在Seata中,有4種分布式事務(wù)實現(xiàn)方案
XA、AT、TCC、Saga
其中XA利用了數(shù)據(jù)庫的分布式事務(wù)特性,AT相當于框架去控制事務(wù)回滾。TCC手寫三個方法,saga手寫兩個方法。
AT的性能和編寫比較折中,是最常用的一種。TCC一些視頻教程中介紹了單表單字段加中間表的方式存儲過程數(shù)據(jù),對于一次操作多個主子表數(shù)據(jù)的示例目前實現(xiàn)還是太繁瑣了。
根據(jù)官方實例和相關(guān)視頻簡單寫了下代碼。
對于配置,能用默認的用默認,有示例配置的優(yōu)先抄示例配置
1.加依賴
<!-- 版本對應(yīng)關(guān)系A(chǔ)libaba 2021.0.5 對應(yīng) Seata 1.6.1https://github.com/alibaba/spring-cloud-alibaba/wiki/%E7%89%88%E6%9C%AC%E8%AF%B4%E6%98%8E這里依賴不是 spring-cloud-alibaba-seata--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-seata</artifactId><version>2021.0.5.0</version></dependency>
這里alibaba版本是2021.0.5所以spring-cloud-starter-alibaba-seata也用這個版本,注意版本對應(yīng)
2.寫配置
seata:registry:type: nacosnacos:application: seata-serverserver-addr: 127.0.0.1:8848group: SEATA_GROUPcluster: default#事務(wù)組tx-service-group: default_tx_groupservice:#事務(wù)組和集群名稱映射vgroup-mapping:default_tx_group: defaultdata-source-proxy-mode: AT
注意,這里需要先配置好nacos和seata服務(wù)端,seata服務(wù)端早期是json配置的,新版的是yaml配置
seata服務(wù)端配置application.yml
# Copyright 1999-2019 Seata.io Group.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.server:port: 7091spring:application:name: seata-serverlogging:config: classpath:logback-spring.xmlfile:path: ${log.home:${user.home}/logs/seata}extend:logstash-appender:destination: 127.0.0.1:4560kafka-appender:bootstrap-servers: 127.0.0.1:9092topic: logback_to_logstashconsole:user:username: seatapassword: seata
seata:config:# support: nacos, consul, apollo, zk, etcd3type: fileregistry:# support: nacos, eureka, redis, zk, consul, etcd3, sofatype: nacosnacos:application: seata-serverserver-addr: 127.0.0.1:8848group: SEATA_GROUPnamespace:cluster: defaultusername:password:context-path:store:# support: file 、 db 、 redismode: file
# server:
# service-port: 8091 #If not configured, the default is '${server.port} + 1000'security:secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017tokenValidityInMilliseconds: 1800000ignore:urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.jpeg,/**/*.ico,/api/v1/auth/login
3.寫代碼
將主調(diào)用的方法注解@Transactional改為@GlobalTransactional,其他微服務(wù)方法無需更改。
完整代碼見頂部