Seata如何搭建與分布式事務(wù)入門

本篇內(nèi)容主要講解“Seata如何搭建與分布式事務(wù)入門”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“Seata如何搭建與分布式事務(wù)入門”吧!

創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供奈曼網(wǎng)站建設(shè)、奈曼做網(wǎng)站、奈曼網(wǎng)站設(shè)計、奈曼網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計與制作、奈曼企業(yè)網(wǎng)站模板建站服務(wù),10多年奈曼做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。

在單體架構(gòu)下,我們大多使用的是單體數(shù)據(jù)庫,通過數(shù)據(jù)庫的ACID特性支持,實現(xiàn)了本地事務(wù)。但是在微服務(wù)架構(gòu)下復(fù)雜的業(yè)務(wù)關(guān)系中,分布式事務(wù)是不可避免的問題之一。Seata是Spring Cloud Alibaba分布式事務(wù)解決方案中間件,解決了微服務(wù)場景下面臨的分布式事務(wù)問題。本文介紹如何通過搭建Seata環(huán)境,并通過其AT模式,實現(xiàn)分布式事務(wù)。

本文中使用的環(huán)境版本:

nacos-server-1.3.1 seata-server-1.4.0 spring-cloud Hoxton.SR3 spring-cloud-alibaba 2.2.1.RELEASE

1、Seata服務(wù)安裝包下載

下載seata-server-1.4.0: https://github.com/seata/seata/releases/tag/v1.4.0 同時下載seata-server-0.0.9,需要其中的配置文件和腳本: https://github.com/seata/seata/releases/tag/v0.9.0

2、Seata服務(wù)配置

在conf目錄下,先把配置文件備份后再進行更改

  • 修改file.conf,mode選擇數(shù)據(jù)庫模式,并配置數(shù)據(jù)庫連接信息

  ## store mode: file、db、redis
  mode = "db"
  ## database store property
  db {
    ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp)/HikariDataSource(hikari) etc.
    datasource = "druid"
    ## MySQL/oracle/postgresql/h3/oceanbase etc.
    dbType = "mysql"
    driverClassName = "com.mysql.jdbc.Driver"
    url = "jdbc:mysql://127.0.0.1:3306/seata"
    user = "hydra"
    password = "123456"
    minConn = 5
    maxConn = 100
    globalTable = "global_table"
    branchTable = "branch_table"
    lockTable = "lock_table"
    queryLimit = 100
    maxWait = 5000
  }
  • 修改registry.conf,使用nacos作為注冊和配置中心??梢栽趎acos中創(chuàng)建一個命名空間,把生成的命名空間的值拷過來

  registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "nacos"
  
    nacos {
    application = "seata-server"
    serverAddr = "127.0.0.1:8848"
    group = "SEATA_GROUP"
    namespace = "202274f4-218e-42bf-9251-e996df6340f8"
    cluster = "default"
    username = "nacos"
    password = "nacos"
  }
  
  
  config {
  # file、nacos 、apollo、zk、consul、etcd3
  type = "nacos"

  nacos {
    serverAddr = "127.0.0.1:8848"
    namespace = "202274f4-218e-42bf-9251-e996df6340f8"
    group = "SEATA_GROUP"
    username = "nacos"
    password = "nacos"
  }
3、導(dǎo)入Seate參數(shù)配置到nacos配置中心

首先,把seata-server-0.9的 nacos-config.txt 和nacos-config.sh腳本拷貝到1.4版本的 seata/conf下。我們需要把nacos-config.txt的參數(shù)通過腳本nacos-config.sh導(dǎo)入到nacos配置中心,之后微服務(wù)項目也從nacos配置中心讀取配置。這樣就不用像老版本那樣,需要把兩個配置文件拷到微服務(wù)項目的resourcce目錄下了。

修改nacos-config.txt,首先修改數(shù)據(jù)庫配置:

store.mode=db
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true
store.db.user=hydra
store.db.password=123456

0.9中的參數(shù)格式還是使用橫線模式,在1.4中規(guī)范有所變動,需要把橫線變成駝峰,啟動需要改動的參數(shù)有:

store.db.db-type=mysql
store.db.driver-class-name=com.mysql.jdbc.Driver

需要改成駝峰:

store.db.dbType=mysql
store.db.driverClassName=com.mysql.jdbc.Driver

并且,如果使用的是mysql8.0以上的版本,需要改一下驅(qū)動的名稱。

其他參數(shù)的具體意義可以查看官方文檔: https://seata.io/zh-cn/docs/user/configurations.html,并按照上面的規(guī)則進行修改。額外需要注意參數(shù)的參數(shù)是: service.vgroup_mapping

service.vgroup_mapping.my_test_tx_group=default

官方解釋為事務(wù)群組,具體使用多少個事務(wù)群體沒有明確指出。但通過查看文檔和部分開源項目發(fā)現(xiàn),大多都采用將key值設(shè)置為服務(wù)端的服務(wù)名,有多少個微服務(wù)就添加多少行。在接下來的demo中要使用兩個微服務(wù)作為示例,因此添加:

service.vgroupMapping.order-service-group=default
service.vgroupMapping.stock-service-group=default

使用gitbash運行nacos-config.sh腳本,參數(shù)是nacos的ip:

sh nacos-config.sh 127.0.0.1

這樣執(zhí)行完成后參數(shù)默認(rèn)是存在nacos config的public命名空間下,可以在nacos創(chuàng)建一個seata的命名空間,把所有參數(shù)拷貝過去,方便進行區(qū)分。

4、建表

在seata數(shù)據(jù)庫中新建表branch_table, global_table, lock_table,在業(yè)務(wù)數(shù)據(jù)庫中新建表undo_log,用于回滾,這些腳本在seata-server-0.9中也可以直接找到。

-- the table to store GlobalSession data
drop table if exists `global_table`;
create table `global_table` (
  `xid` varchar(128)  not null,
  `transaction_id` bigint,
  `status` tinyint not null,
  `application_id` varchar(32),
  `transaction_service_group` varchar(32),
  `transaction_name` varchar(128),
  `timeout` int,
  `begin_time` bigint,
  `application_data` varchar(2000),
  `gmt_create` datetime,
  `gmt_modified` datetime,
  primary key (`xid`),
  key `idx_gmt_modified_status` (`gmt_modified`, `status`),
  key `idx_transaction_id` (`transaction_id`)
);
 
-- the table to store BranchSession data
drop table if exists `branch_table`;
create table `branch_table` (
  `branch_id` bigint not null,
  `xid` varchar(128) not null,
  `transaction_id` bigint ,
  `resource_group_id` varchar(32),
  `resource_id` varchar(256) ,
  `lock_key` varchar(128) ,
  `branch_type` varchar(8) ,
  `status` tinyint,
  `client_id` varchar(64),
  `application_data` varchar(2000),
  `gmt_create` datetime,
  `gmt_modified` datetime,
  primary key (`branch_id`),
  key `idx_xid` (`xid`)
);
 
-- the table to store lock data
drop table if exists `lock_table`;
create table `lock_table` (
  `row_key` varchar(128) not null,
  `xid` varchar(96),
  `transaction_id` long ,
  `branch_id` long,
  `resource_id` varchar(256) ,
  `table_name` varchar(32) ,
  `pk` varchar(36) ,
  `gmt_create` datetime ,
  `gmt_modified` datetime,
  primary key(`row_key`)
);
 
-- the table to store seata xid data
-- 0.7.0+ add context
-- you must to init this sql for you business databese. the seata server not need it.
-- 此腳本必須初始化在你當(dāng)前的業(yè)務(wù)數(shù)據(jù)庫中,用于AT 模式XID記錄。與server端無關(guān)(注:業(yè)務(wù)數(shù)據(jù)庫)
-- 注意此處0.3.0+ 增加唯一索引 ux_undo_log
drop table `undo_log`;
CREATE TABLE `undo_log` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `branch_id` bigint(20) NOT NULL,
  `xid` varchar(100) NOT NULL,
  `context` varchar(128) NOT NULL,
  `rollback_info` longblob NOT NULL,
  `log_status` int(11) NOT NULL,
  `log_created` datetime NOT NULL,
  `log_modified` datetime NOT NULL,
  `ext` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
5、啟動

在啟動nacos-server后,點擊 seata/bin/seata-server.bat啟動seata。

6、微服務(wù)改造
  • 在微服務(wù)中引入seata的依賴:

<dependency>
    <groupId>io.seata</groupId>
    <artifactId>seata-spring-boot-starter</artifactId>
    <version>1.3.0</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>
</dependency>

如果微服務(wù)中使用的是druid連接池,可以把已有的druid依賴刪除,在seata-spring-boot-starter-1.3.0中已經(jīng)引入了druid-1.1.12。

  • 修改每一個微服務(wù)yml,主要是配置nacos和seata,tx-service-group就是nacos-config.txt 中 service.vgroupMapping的key,我們這里使用微服務(wù)的名稱加上group后綴

server:
  port: 8763

spring:
  application:
    name: order-service
  cloud:
    nacos:
      server-addr: 127.0.0.1:8848
  datasource:
    url: jdbc:mysql://localhost:3306/tenant?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: hydra
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      initial-size: 8
      min-idle: 1
      max-active: 10
      max-wait: 60000

seata:
  enabled: true
  application-id: ${spring.application.name}
  tx-service-group: ${spring.application.name}-group
  enable-auto-data-source-proxy: true
  config:
    type: nacos
    nacos:
      server-addr: 127.0.0.1:8848
      namespace: 202274f4-218e-42bf-9251-e996df6340f8
      group: SEATA_GROUP
      username: nacos
      password: nacos
  registry:
    type: nacos
    nacos:
      application: seata-server
      server-addr: 127.0.0.1:8848
      namespace: 202274f4-218e-42bf-9251-e996df6340f8
      group: SEATA_GROUP
      username: nacos
      password: nacos
#  service:
#    vgroupMapping:
#      order-service-group: default

mybatis-plus:
  mapper-locations: classpath:mapper/*Mapper.xml
  type-aliases-package: com.cn.nacos.consumer.entity
  • 配置seata的數(shù)據(jù)庫代理,在使用mybatis-plus時的配置方式如下:

@Configuration
public class DataSourceProxyConfig {
    @Bean
    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
        // 訂單服務(wù)中引入了mybatis-plus,所以要使用特殊的SqlSessionFactoryBean
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        // 代理數(shù)據(jù)源
        sqlSessionFactoryBean.setDataSource(new DataSourceProxy(dataSource));
        // 生成SqlSessionFactory
        return sqlSessionFactoryBean.getObject();
    }
}
  • 調(diào)用測試,OrderService調(diào)用StockService為例,在被調(diào)用的service方法上加上@Transactional注解

StockService提供接口:

@Service
public class StockService {
    @Autowired
    private StockMapper stockMapper;

    @Transactional
    public String reduce(){
        System.out.println("減庫存");

        Stock stock = stockMapper.selectOne(new LambdaQueryWrapper<Stock>().eq(Stock::getId, 1));
        System.out.println(stock.toString());

        stock.setQuantity(stock.getQuantity()-1);
        int result = stockMapper.updateById(stock);
        System.out.println("update result: "+result);

        if (result==1){
            throw new RuntimeException("異常測試,準(zhǔn)備rollBack");
        }
        return "stock reduce success";
    }
}

OrderService調(diào)用StockService的服務(wù),使用了FeignClient調(diào)用StockService,并在發(fā)起事務(wù)的方法上加上@GlobalTransactional注解:

@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StockClient stockClient;

    @GlobalTransactional
    public String buy(){
        Order order=new Order();
        order.setId(1L).setMoney(20D);
        int result = orderMapper.insert(order);

        if (result==1){
            System.out.println("插入訂單成功");
        }
        return stockClient.reduce();
    }
}

調(diào)用OrderService的接口,會在StockService中拋出異常,reduce方法中的本地事務(wù)先執(zhí)行回滾。再查看日志,在order表上執(zhí)行了回滾操作:

Seata如何搭建與分布式事務(wù)入門

在上面的日志中,打印出了全局事務(wù)的xid、分支的branchId、以及seata使用的模式,在使用AT模式的二階段提交完成后,顯示回滾狀態(tài)為回滾完成。查看業(yè)務(wù)數(shù)據(jù)庫的und_log表,已經(jīng)插入了回滾記錄:

Seata如何搭建與分布式事務(wù)入門

這樣,就以Seata中默認(rèn)的AT模式實現(xiàn)了分布式事務(wù)。在該模式下,可以應(yīng)對大多數(shù)的業(yè)務(wù)場景,并且基本可以做到無業(yè)務(wù)入侵,對于程序員來說,只需要添加注解,不需要做其他的業(yè)務(wù)功能改造,就可以以無感知的方式就可以實現(xiàn)分布式事務(wù)的解決。

到此,相信大家對“Seata如何搭建與分布式事務(wù)入門”有了更深的了解,不妨來實際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

當(dāng)前文章:Seata如何搭建與分布式事務(wù)入門
本文鏈接:http://muchs.cn/article30/ihgopo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供移動網(wǎng)站建設(shè)、小程序開發(fā)、Google電子商務(wù)、定制開發(fā)、關(guān)鍵詞優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都seo排名網(wǎng)站優(yōu)化