seata使用配置文件集成

  1. 我這里是Centos7,第一步先安裝java環(huán)境佩脊;
  2. 下載steata包,下載地址:seata1.4.2
  3. 上傳到linux的/software/目錄后解壓
cd /software/
tar -zxvf seata-server-1.4.2.tar.gz
cd /seata/seata-server-1.4.2

4.修改registry.conf文件

registry {
  # file 亲茅、nacos 颁股、eureka、redis征绸、zk久橙、consul、etcd3管怠、sofa
  # 指定注冊中心為eureka淆衷,以下只需要配置eureka相關(guān)配置參數(shù)即可
  type = "eureka"

  nacos {
    application = "seata-server"
    serverAddr = "127.0.0.1:8848"
    group = "SEATA_GROUP"
    namespace = ""
    cluster = "default"
    username = ""
    password = ""
  }
  eureka {
    #修改了宿主機的hosts,將注冊中心的ip統(tǒng)一為指定域名渤弛,方便維護
    serviceUrl = "http://127.0.0.1:8761/eureka"
    #自定義注冊中心服務名
    application = "SEATA"
    weight = "1"
  }
  redis {
    serverAddr = "localhost:6379"
    db = 0
    password = ""
    cluster = "default"
    timeout = 0
  }
  zk {
    cluster = "default"
    serverAddr = "127.0.0.1:2181"
    sessionTimeout = 6000
    connectTimeout = 2000
    username = ""
    password = ""
  }
  consul {
    cluster = "default"
    serverAddr = "127.0.0.1:8500"
    aclToken = ""
  }
  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 = "127.0.0.1:8848"
    namespace = ""
    group = "SEATA_GROUP"
    username = ""
    password = ""
    dataId = "seataServer.properties"
  }
  consul {
    serverAddr = "127.0.0.1:8500"
    aclToken = ""
  }
  apollo {
    appId = "seata-server"
    ## apolloConfigService will cover apolloMeta
    apolloMeta = "http://192.168.1.204:8801"
    apolloConfigService = "http://192.168.1.204:8080"
    namespace = "application"
    apolloAccesskeySecret = ""
    cluster = "seata"
  }
  zk {
    serverAddr = "127.0.0.1:2181"
    sessionTimeout = 6000
    connectTimeout = 2000
    username = ""
    password = ""
    nodePath = "/seata/seata.properties"
  }
  etcd3 {
    serverAddr = "http://localhost:2379"
  }
  file {
    # 存儲模式的配置
    name = "file.conf"
  }
}

5.修改file.conf

## transaction log store, only used in seata-server
store {
  ## store mode: file晴氨、db康嘉、redis
  # 指定存儲模式為db,集群必須配置為db
  mode = "db"
  ## file store property
  file {
    ## store location dir
    dir = "sessionStore"
    # branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions
    maxBranchSessionSize = 16384
    # globe session size , if exceeded throws exceptions
    maxGlobalSessionSize = 512
    # file buffer size , if exceeded allocate new buffer
    fileWriteBufferCacheSize = 16384
    # when recover batch read size
    sessionReloadReadSize = 100
    # async, sync
    flushDiskMode = async
  }

  ## database store property
  # 第一步創(chuàng)建數(shù)據(jù)表的數(shù)據(jù)庫配置參數(shù)
  db {
    ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp)/HikariDataSource(hikari) etc.
    datasource = "druid"
    ## mysql/oracle/postgresql/h2/oceanbase etc.
    dbType = "mysql"
    driverClassName = "com.mysql.cj.jdbc.Driver"
    ## if using mysql to store the data, recommend add rewriteBatchedStatements=true in jdbc connection param
    url = "jdbc:mysql://xxx:3306/test_seata"
    user = "xxx"
    password = "xxx"
    minConn = 5
    maxConn = 100
    globalTable = "global_table"
    branchTable = "branch_table"
    lockTable = "lock_table"
    queryLimit = 100
    maxWait = 5000
  }

  ## redis store property
  redis {
    ## redis mode: single籽前、sentinel
    mode = "single"
    ## single mode property
    single {
      host = "127.0.0.1"
      port = "6379"
    }
    ## sentinel mode property
    sentinel {
      masterName = ""
      ## such as "10.28.235.65:26379,10.28.235.65:26380,10.28.235.65:26381"
      sentinelHosts = ""
    }
    password = ""
    database = "0"
    minConn = 1
    maxConn = 10
    maxTotal = 100
    queryLimit = 100
  }
}
  1. 啟動
#在test_seata數(shù)據(jù)庫建以下幾張表凄鼻,建表語句:
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`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

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`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

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`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

#后臺運行
nohup ./bin/seata-server.sh -p 8091 -h 127.0.0.1 -m db &> ./logs/seata.log &
#查看日志,看到-Server started即成功聚假,再打開eureka是否有注冊上去
tail -f ./logs/seata.log
  • -p 指定啟動seata server的端口號块蚌;
  • -h 指定seata server所綁定的主機;
  • -m 事務日志膘格、事務執(zhí)行信息存儲的方式峭范,目前支持file(文件方式)、db(數(shù)據(jù)庫方式瘪贱,建表語句請查看步驟6)
  1. 在項目中使用纱控,添加依賴:
      <dependency>
          <groupId>com.alibaba.cloud</groupId>
          <artifactId>spring-cloud-alibaba-seata</artifactId>
          <version>2.2.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>io.seata</groupId>
          <artifactId>seata-all</artifactId>
          <version>0.8.1</version>
      </dependency>

8.將下面的file.conf和registry.conf復制到resources目錄下:

  • file.config
transport {
  # tcp udt unix-domain-socket
  type = "TCP"
  #NIO NATIVE
  server = "NIO"
  #enable heartbeat
  heartbeat = true
  # the client batch send request enable
  enable-client-batch-send-request = 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 {
  #transaction service group mapping
  # 指定TC服務,order_seata_server與yml中對應
  vgroupMapping.order_seata_server="SEATA"
  #only support when registry.type=file, please don't set multiple addresses
  # 這個參數(shù)集群環(huán)境不需要配置 只有當registry.type=file,注冊中心是file方式時菜秦,才會起作用
  SEATA.grouplist = "127.0.0.1:8091"
  #degrade, current not support
  enableDegrade = false
  #disable seata
  disableGlobalTransaction = false
}
client {
  rm {
    async.commit.buffer.limit = 10000
    lock {
      retry.internal = 10
      retry.times = 30
      retry.policy.branch-rollback-on-conflict = true
    }
    report.retry.count = 5
    table.meta.check.enable = false
    report.success.enable = true
  }
  tm {
    commit.retry.count = 5
    rollback.retry.count = 5
  }
  undo {
    data.validation = true
    log.serialization = "jackson"
    #指定回滾日志表名稱
    log.table = "undo_log"
  }
  log {
    exceptionRate = 100
  }
  support {
    # auto proxy the DataSource bean
    spring.datasource.autoproxy = false
  }
}
  • registry.conf
registry {
 # file 甜害、nacos 、eureka球昨、redis尔店、zk、consul、etcd3嚣州、sofa
 type = "eureka"
 nacos {
   serverAddr = "localhost"
   namespace = ""
   cluster = "default"
 }
 eureka {
   serviceUrl = "http://127.0.0.1:8761/eureka"
   application = "order-seata-server"
   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"
 }
}
  1. application.yml中添加:
spring:
  cloud:
    alibaba:
      seata:
        tx-service-group: order_seata_server
  1. 使用DataSourceProxy代理數(shù)據(jù)源匀哄,mybatis配置需要加上SqlSessionFactory :

import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class DataSourceProxyConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    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();
    }

}
  1. 在你需要使用feign進行微服務間調(diào)到的方法上添加注解@GlobalTransactional


    注解
  2. 每個涉及到分布式事務的微服務的數(shù)據(jù)庫都要有一張undo_log日志表秦效,sql如下:

DROP TABLE IF EXISTS `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=utf8mb4 COLLATE=utf8mb4_general_ci;
  1. 在需要微服務調(diào)用的微服務中進行以上相同配置(7.8.9.10.12),除了@GlobalTransactional注解,之后便可以拋出異诚呀溃看是否回滾成功
  • 注:seata集群只需要再以其他端口啟動seata文件目錄即可


    seata集群
  1. docker-compose編排部署:
version: "3"
services:
  seata-server:
    image: seataio/seata-server:1.4.2
    container_name: seata-server
    hostname: seata-server
    networks:
      - seata-server
    ports:
      - "8091:8091"
    environment:
      #宿主機ip
      - SEATA_PORT=8091
      # 指定seata-server的事務日志存儲方式, 支持db ,file(默認),redis
      - STORE_MODE=db
      #seata的被發(fā)現(xiàn)地址棉安,該IP用于向注冊中心注冊時使用(也就是自身的ip)
      - SEATA_IP=127.0.0.1
      #給予權(quán)限
      #- privileged=true
    volumes:
      - /software/docker/seata/config/registry.conf:/seata-server/resources/registry.conf
      - /software/docker/seata/config/file.conf:/seata-server/resources/file.conf
      - /software/docker/seata/mysql-connector-java-8.0.16.jar:/seata-server/libs/mysql-connector-java-8.0.16.jar
      - /project/docker/seata/logs:/root/logs/seata
      - /etc/localtime:/etc/localtime
networks:
  seata-server:
    driver: bridge

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市铸抑,隨后出現(xiàn)的幾起案子贡耽,更是在濱河造成了極大的恐慌,老刑警劉巖鹊汛,帶你破解...
    沈念sama閱讀 216,544評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蒲赂,死亡現(xiàn)場離奇詭異,居然都是意外死亡刁憋,警方通過查閱死者的電腦和手機滥嘴,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來至耻,“玉大人若皱,你說我怎么就攤上這事〕就牵” “怎么了走触?”我有些...
    開封第一講書人閱讀 162,764評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長疤苹。 經(jīng)常有香客問我互广,道長,這世上最難降的妖魔是什么卧土? 我笑而不...
    開封第一講書人閱讀 58,193評論 1 292
  • 正文 為了忘掉前任惫皱,我火速辦了婚禮,結(jié)果婚禮上尤莺,老公的妹妹穿的比我還像新娘旅敷。我一直安慰自己,他們只是感情好颤霎,可當我...
    茶點故事閱讀 67,216評論 6 388
  • 文/花漫 我一把揭開白布媳谁。 她就那樣靜靜地躺著涂滴,像睡著了一般。 火紅的嫁衣襯著肌膚如雪韩脑。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,182評論 1 299
  • 那天粹污,我揣著相機與錄音段多,去河邊找鬼。 笑死壮吩,一個胖子當著我的面吹牛进苍,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播鸭叙,決...
    沈念sama閱讀 40,063評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼觉啊,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了沈贝?” 一聲冷哼從身側(cè)響起杠人,我...
    開封第一講書人閱讀 38,917評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎宋下,沒想到半個月后嗡善,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,329評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡学歧,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,543評論 2 332
  • 正文 我和宋清朗相戀三年罩引,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片枝笨。...
    茶點故事閱讀 39,722評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡袁铐,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出横浑,到底是詐尸還是另有隱情剔桨,我是刑警寧澤,帶...
    沈念sama閱讀 35,425評論 5 343
  • 正文 年R本政府宣布徙融,位于F島的核電站领炫,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏张咳。R本人自食惡果不足惜帝洪,卻給世界環(huán)境...
    茶點故事閱讀 41,019評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望脚猾。 院中可真熱鬧葱峡,春花似錦、人聲如沸龙助。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,671評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至军援,卻和暖如春仅淑,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背胸哥。 一陣腳步聲響...
    開封第一講書人閱讀 32,825評論 1 269
  • 我被黑心中介騙來泰國打工涯竟, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人空厌。 一個月前我還...
    沈念sama閱讀 47,729評論 2 368
  • 正文 我出身青樓庐船,卻偏偏與公主長得像,于是被迫代替她去往敵國和親嘲更。 傳聞我的和親對象是個殘疾皇子筐钟,可洞房花燭夜當晚...
    茶點故事閱讀 44,614評論 2 353

推薦閱讀更多精彩內(nèi)容