Spring Cloud Alibaba Seata

MXC肖某某發表於2020-10-25

一、簡介

官網地址:http://seata.io/zh-cn/

1,概念

  Seata是一款開源的分散式事務解決方案,致力於在微服務架構在提供高效能和簡單一樣的分散式事務服務。

2,處理過程

  Transaction ID XID:全域性唯一的事務ID

  Transaction Coordinator(TC) :維護全域性和分支事務的狀態,驅動全域性事務提交或回滾。

  Transaction  Manager(TM) :定義全域性事務的範圍:開始全域性事務、提交或回滾全域性事務。

  Resource Manager(RM) :管理分支事務處理的資源,與TC交談以註冊分支事務和報告分支事務的狀態,並驅動分支事務提交或回滾。

                   Spring Cloud Alibaba Seata

  1. TM向TC申請開啟一個全域性事務,全域性事務建立成功並生成一個全域性唯一的XID
  2. XID在微服務呼叫鏈路的上下文中傳播
  3. RM向TC註冊分支事務,將其納入XID對應全域性事務的管轄
  4. TM向TC發起針對XID的全域性提交或回滾決議
  5. TC排程XID下管轄的全部分支事務完成提交或回滾請求

二、Seata-Server的安裝

1,下載

  http://seata.io/zh-cn/blog/download.html 選擇指定版本下載(我這裡用的是0.9.0)

2,修改配置檔案

  修改seata/conf/file.conf

#將service中修改group
vgroup_mapping.my_test_tx_group = "my_group"
#將store模組修改為db並修改資料連線,將conf目錄下的db_store.sql檔案匯入到資料庫中
mode = "db"
db {
    datasource = "dbcp"
    db-type = "mysql"
    driver-class-name = "com.mysql.jdbc.Driver"
    url = "jdbc:mysql://127.0.0.1:3306/seata"
    user = "root"
    password = "123456"
}

   修改seata/conf/registry.conf

registry {
  type = "nacos"
  nacos {
    serverAddr = "localhost:8848"
    namespace = ""
    cluster = "default"
 }

三、Seata的應用

1,訂單服務

原始碼:seata-order-service2001

a,配置pom

Spring Cloud Alibaba Seata
<!--nacos-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--seata-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
    <exclusions>
        <exclusion>
            <artifactId>seata-all</artifactId>
            <groupId>io.seata</groupId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>io.seata</groupId>
    <artifactId>seata-all</artifactId>
    <version>0.9.0</version>
</dependency>
<!--feign-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--web-actuator-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--mysql-druid-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.37</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.0</version>
</dependency>
View Code

b,配置yaml

Spring Cloud Alibaba Seata
server:
  port: 2001

spring:
  application:
    name: seata-order-service
  cloud:
    alibaba:
      seata:
        #自定義事務組名稱需要與seata-server中的對應
        tx-service-group: my_group
    nacos:
      discovery:
        server-addr: localhost:8848
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/seata_order
    username: root
    password: 123456

feign:
  hystrix:
    enabled: false

logging:
  level:
    io:
      seata: info

mybatis:
  mapperLocations: classpath:mapper/*.xml
View Code

c,新增file.conf(與seata-server配置相同)

Spring Cloud Alibaba Seata
transport {
  # tcp udt unix-domain-socket
  type = "TCP"
  #NIO NATIVE
  server = "NIO"
  #enable heartbeat
  heartbeat = true
  #thread factory for netty
  thread-factory {
    boss-thread-prefix = "NettyBoss"
    worker-thread-prefix = "NettyServerNIOWorker"
    server-executor-thread-prefix = "NettyServerBizHandler"
    share-boss-worker = false
    client-selector-thread-prefix = "NettyClientSelector"
    client-selector-thread-size = 1
    client-worker-thread-prefix = "NettyClientWorkerThread"
    # netty boss thread size,will not be used for UDT
    boss-thread-size = 1
    #auto default pin or 8
    worker-thread-size = 8
  }
  shutdown {
    # when destroy server, wait seconds
    wait = 3
  }
  serialization = "seata"
  compressor = "none"
}

service {

  vgroup_mapping.my_group = "default"

  default.grouplist = "127.0.0.1:8091"
  enableDegrade = false
  disable = false
  max.commit.retry.timeout = "-1"
  max.rollback.retry.timeout = "-1"
  disableGlobalTransaction = false
}


client {
  async.commit.buffer.limit = 10000
  lock {
    retry.internal = 10
    retry.times = 30
  }
  report.retry.count = 5
  tm.commit.retry.count = 1
  tm.rollback.retry.count = 1
}

## transaction log store
store {
  ## store mode: file、db
  mode = "db"

  ## file store
  file {
    dir = "sessionStore"

    # branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions
    max-branch-session-size = 16384
    # globe session size , if exceeded throws exceptions
    max-global-session-size = 512
    # file buffer size , if exceeded allocate new buffer
    file-write-buffer-cache-size = 16384
    # when recover batch read size
    session.reload.read_size = 100
    # async, sync
    flush-disk-mode = async
  }

  ## database store
  db {
    ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp) etc.
    datasource = "dbcp"
    ## mysql/oracle/h2/oceanbase etc.
    db-type = "mysql"
    driver-class-name = "com.mysql.jdbc.Driver"
    url = "jdbc:mysql://127.0.0.1:3306/seata"
    user = "root"
    password = "123456"
    min-conn = 1
    max-conn = 3
    global.table = "global_table"
    branch.table = "branch_table"
    lock-table = "lock_table"
    query-limit = 100
  }
}
lock {
  ## the lock store mode: local、remote
  mode = "remote"

  local {
    ## store locks in user's database
  }

  remote {
    ## store locks in the seata's server
  }
}
recovery {
  #schedule committing retry period in milliseconds
  committing-retry-period = 1000
  #schedule asyn committing retry period in milliseconds
  asyn-committing-retry-period = 1000
  #schedule rollbacking retry period in milliseconds
  rollbacking-retry-period = 1000
  #schedule timeout retry period in milliseconds
  timeout-retry-period = 1000
}

transaction {
  undo.data.validation = true
  undo.log.serialization = "jackson"
  undo.log.save.days = 7
  #schedule delete expired undo_log in milliseconds
  undo.log.delete.period = 86400000
  undo.log.table = "undo_log"
}

## metrics settings
metrics {
  enabled = false
  registry-type = "compact"
  # multi exporters use comma divided
  exporter-list = "prometheus"
  exporter-prometheus-port = 9898
}

support {
  ## spring
  spring {
    # auto proxy the DataSource bean
    datasource.autoproxy = false
  }
}
View Code

d,新增registry.conf(與seata-server的配置相同)

Spring Cloud Alibaba Seata
registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "nacos"

  nacos {
    serverAddr = "localhost:8848"
    namespace = ""
    cluster = "default"
  }
  eureka {
    serviceUrl = "http://localhost:8761/eureka"
    application = "default"
    weight = "1"
  }
  redis {
    serverAddr = "localhost:6379"
    db = "0"
  }
  zk {
    cluster = "default"
    serverAddr = "127.0.0.1:2181"
    session.timeout = 6000
    connect.timeout = 2000
  }
  consul {
    cluster = "default"
    serverAddr = "127.0.0.1:8500"
  }
  etcd3 {
    cluster = "default"
    serverAddr = "http://localhost:2379"
  }
  sofa {
    serverAddr = "127.0.0.1:9603"
    application = "default"
    region = "DEFAULT_ZONE"
    datacenter = "DefaultDataCenter"
    cluster = "default"
    group = "SEATA_GROUP"
    addressWaitTime = "3000"
  }
  file {
    name = "file.conf"
  }
}

config {
  # file、nacos 、apollo、zk、consul、etcd3
  type = "file"

  nacos {
    serverAddr = "localhost"
    namespace = ""
  }
  consul {
    serverAddr = "127.0.0.1:8500"
  }
  apollo {
    app.id = "seata-server"
    apollo.meta = "http://192.168.1.204:8801"
  }
  zk {
    serverAddr = "127.0.0.1:2181"
    session.timeout = 6000
    connect.timeout = 2000
  }
  etcd3 {
    serverAddr = "http://localhost:2379"
  }
  file {
    name = "file.conf"
  }
}
View Code

e,fegin呼叫(這裡以其中一個account為例)

Spring Cloud Alibaba Seata
@FeignClient(value = "seata-account-service")
public interface AccountService {

    @RequestMapping("/account/decrease")
    public CommonResult decrease(@RequestParam("userId") Long userId, @RequestParam("money") BigDecimal money);

}
View Code

f,事務service

Spring Cloud Alibaba Seata
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderDao orderDao;
    @Autowired
    AccountService accountService;
    @Autowired
    StorageService storageService;

    @Override
    @GlobalTransactional(name = "my-order-test",rollbackFor = Exception.class) //加註解使用全域性的事務,name 為事務名稱不重複就行
    public Long create(Order order) {
        log.info("=========================下訂單,開始");
        orderDao.create(order);
        log.info("=========================下訂單,完成");

        log.info("=========================減庫存,開始");
        storageService.decrease(order.getProductId(), order.getCount());
        log.info("=========================減庫存,完成");

        log.info("=========================減積分,開始");
        accountService.decrease(order.getUserId(), order.getMoney());
        log.info("=========================減積分,完成");

        log.info("=========================訂單狀態修改,開始");
        orderDao.update(order.getId(),1);
        log.info("=========================訂單狀態修改,完成");

        return order.getId();
    }
}
View Code

g,啟動類

Spring Cloud Alibaba SeataView Code

2,庫存服務

原始碼:seata-storage-service2002

  與訂單服務中的a,b,c,d,g配置步驟相同

3,賬戶服務

原始碼:seata-account-service2003

  與庫存服務的配置步驟相同

四、Seata的原理解析

參考文件:http://seata.io/zh-cn/docs/overview/what-is-seata.html

1,AT模式

一階段

 

1,解析SQL語義,找到"業務SQL"要更新的業務資料,在業務資料被更新前,將其儲存成"before image"
2,執行"業務SQL"更新業務資料,在業務數更新之後
3,將其儲存成"after image",最後生成行鎖。
以上操作全部在一個資料庫事務內完成,這樣保證了一階段操作的原子性。

 

                 Spring Cloud Alibaba Seata

二階段提交

因為"業務SQL"在一階段已經提交至資料庫,所以seata框架只需將一階段儲存的快照資料和行鎖刪掉,完成資料清理即可。

                 Spring Cloud Alibaba Seata

 

 

二階段回滾

二階段如果是回滾的話,seata就需要回滾一階段已經執行的"業務SQL",還原業務資料。

回滾的方式便是用"before image"還原業務資料;但在還原前要首先校驗髒寫,對比"資料庫當前業務資料"和"after image"

如果兩份資料完全一致就說明沒有髒寫,可以還原業務資料,如果不一致就說明有髒寫,出現髒寫就需要轉人工處理。

                 Spring Cloud Alibaba Seata

 

 

  

 

相關文章