四春の雲seataデモ

はじめに

Seata分散トランザクションに基づいて、デモバンク
AおよびバンクBサービスは
ソースコードアドレスを転送します:https : //gitee.com/xrzi2016/spring-cloud-seata-demo

使用説明書

  1. Seata-serverを起動します:sh ./bin/seata-server.sh
    image.png

  2. Seata-commonをローカルファクトリライブラリにインストールします:mvn install
    image.png

  3. 登録センターを起動します:mvn spring-boot:run
    image.png

  4. 启动bank-a:mvn spring-boot:run
    image.png

Seata-serveの出力を見るimage.png

  1. 启动bank-b:mvn spring-boot:run
    image.png

Seata-serveの出力を見るimage.png

使用説明書

  1. 通常のテスト:http://127.0.0.1:8081/bank-a/updAmount

    銀行-図書館の張さん口座100元
    image.png

    Bank-b Li Siアカウントは100元を差し引きます image.png

  2. 異常なテスト:http://127.0.0.1:8081/bank-a/updAmount?mode=OUT

    銀行A銀行と銀行B銀行の金額は変更されません。
    image.png

    Seata-serve出力ロールバック情報を参照してくださいimage.png

Spring CloudはSeataをすばやく統合します

公式アドレス:http://seata.io/zh-cn/

官方Github:https://github.com/seata/seata-samples/blob/master/doc/quick-integration-with-spring-cloud.md#registryconf

1.依存関係を追加する

メイベン

<dependency>
	<groupId>com.alibaba.cloud</groupId>
	<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
        <version>2.1.0.RELEASE</version>
</dependency>

Spring Cloud Alibabaの段階的バージョンのGroupIdはcom.alibaba.cloudであることに注意してください。

spring-cloud-starter-alibaba-seataはspring-cloud-alibaba-seataにのみ依存するため、プロジェクトにspring-cloud-starter-alibaba-seataとspring-cloud-alibaba-seataを追加することは同じです

2. Seata構成ファイルを追加します

registry.conf
この構成は、TCのレジストリと構成ファイルを指定するために使用されます。デフォルトはfileです。別のレジストリを使用する場合、構成センターに登録するためにSeata-Serverも必要です

registry.conf

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "file"

  nacos {
    serverAddr = "localhost"
    namespace = "public"
    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 = "public"
    cluster = "default"
  }
  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"
  }
}

file.conf
この構成は、TCの関連属性を指定するために使用されます。登録センターを使用する場合、構成を構成センターに追加することもできます。

file.conf

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->rgroup
  vgroup_mapping.my_test_tx_group = "default"
  #only support single node
  default.grouplist = "127.0.0.1:8091"
  #degrade current not support
  enableDegrade = false
  #disable
  disable = false
  #unit ms,s,m,h,d represents milliseconds, seconds, minutes, hours, days, default permanent
  max.commit.retry.timeout = "-1"
  max.rollback.retry.timeout = "-1"
}

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

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

  ## 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"
    url = "jdbc:mysql://127.0.0.1:3306/seata"
    user = "mysql"
    password = "mysql"
    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 {
  committing-retry-delay = 30
  asyn-committing-retry-delay = 30
  rollbacking-retry-delay = 30
  timeout-retry-delay = 30
}

transaction {
  undo.data.validation = true
  undo.log.serialization = "jackson"
}

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

Spring Cloudでは、service.vgroup_mappingの構成はデフォルトで$ {spring.application.name} -fescar-service-groupです。application.propertiesでspring.cloud.alibaba.seata.tx-service-を指定できます。 group属性はカバーされていますが、file.confと一致している必要があります。そうでない場合、接続できるサーバーがありません。

3.データソースを挿入する

Seataはデータソースをプロキシすることでブランチトランザクションを実装します。MyBatisとJPAの両方をio.seata.rm.datasource.DataSourceProxyに注入する必要があります。違いは、MyBatisは追加のorg.apache.ibatis.session.SqlSessionFactoryも注入する必要があることです。

MyBatis

@Configuration
public class DataSourceProxyConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return new DruidDataSource();
    }

    @Bean
    public DataSourceProxy dataSourceProxy(DataSource dataSource) {
        return new DataSourceProxy(dataSource);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSourceProxy);
        return sqlSessionFactoryBean.getObject();
    }
}

4. undo_logテーブルを追加します

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. Seata-Serverを起動します

対応するバージョンのhttps://github.com/seata/seata/releasesでSeata-Serverをダウンロードし、registry.confを対応する構成に変更し(ファイルを使用する場合は変更する必要はありません)、解凍して次のコマンドで開始します。

sh ./bin/seata-server.sh

6. @GlobalTransactionalを使用してトランザクションを開始します

ビジネス開始者のメソッドで@GlobalTransactionalを使用して、グローバルトランザクションを開始します。シータは、トランザクションのxidをリクエストに追加して、インターセプターを介して他のサービスを呼び出し、分散トランザクションを実装します

公開された15元の記事 ウォンの賞賛0 ビュー75

おすすめ

転載: blog.csdn.net/xrzi2015/article/details/105520344