三. 微服务之springbootalibaba seata注册到 nacos 配置分布式事务

steata文档
本次使用1.3.0版本

1 sql steata服务端sql

create table seata.branch_table
(
    branch_id         bigint        not null
        primary key,
    xid               varchar(128)  not null,
    transaction_id    bigint        null,
    resource_group_id varchar(32)   null,
    resource_id       varchar(256)  null,
    branch_type       varchar(8)    null,
    status            tinyint       null,
    client_id         varchar(64)   null,
    application_data  varchar(2000) null,
    gmt_create        datetime(6)   null,
    gmt_modified      datetime(6)   null
)
    charset = utf8;

create index idx_xid
    on seata.branch_table (xid);



create table seata.global_table
(
    xid                       varchar(128)  not null
        primary key,
    transaction_id            bigint        null,
    status                    tinyint       not null,
    application_id            varchar(32)   null,
    transaction_service_group varchar(32)   null,
    transaction_name          varchar(128)  null,
    timeout                   int           null,
    begin_time                bigint        null,
    application_data          varchar(2000) null,
    gmt_create                datetime      null,
    gmt_modified              datetime      null
)
    charset = utf8;

create index idx_gmt_modified_status
    on seata.global_table (gmt_modified, status);

create index idx_transaction_id
    on seata.global_table (transaction_id);

create table seata.lock_table
(
    row_key        varchar(128) not null
        primary key,
    xid            varchar(96)  null,
    transaction_id bigint       null,
    branch_id      bigint       not null,
    resource_id    varchar(256) null,
    table_name     varchar(32)  null,
    pk             varchar(36)  null,
    gmt_create     datetime     null,
    gmt_modified   datetime     null
)
    charset = utf8;

create index idx_branch_id
    on seata.lock_table (branch_id);




客户端sql 订单模块

create table hq_riderthing_order.undo_log
(
    id            bigint auto_increment
        primary key,
    branch_id     bigint       not null,
    xid           varchar(100) not null,
    context       varchar(128) not null,
    rollback_info longblob     not null,
    log_status    int          not null,
    log_created   datetime     not null,
    log_modified  datetime     not null,
    ext           varchar(100) null,
    constraint ux_undo_log
        unique (xid, branch_id)
)
    charset = utf8;


客户端sql 支付模块

create table hq_riderthing_pay.undo_log
(
    id            bigint auto_increment
        primary key,
    branch_id     bigint       not null,
    xid           varchar(100) not null,
    context       varchar(128) not null,
    rollback_info longblob     not null,
    log_status    int          not null,
    log_created   datetime     not null,
    log_modified  datetime     not null,
    ext           varchar(100) null,
    constraint ux_undo_log
        unique (xid, branch_id)
)
    charset = utf8;

2 seata服务端配置

registry.conf

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

  nacos {
    application = "seata-server"
    serverAddr = "127.0.0.1:8848"
    group = "DEFAULT_GROUP"
    namespace = "98d183cb-132e-4ae9-8f2d-bd2b758cd140"
    cluster = "default"
    #username = ""
    #password = ""
  }
  eureka {
    serviceUrl = "http://localhost:8761/eureka"
    application = "default"
    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"
  }
  etcd3 {
    cluster = "default"
    serverAddr = "http://localhost:2379"
  }
  sofa {
    serverAddr = "127.0.0.1:9603"
    application = "default"
    region = "DEFAULT_ZONE"
    datacenter = "DefaultDataCenter"
    cluster = "default"
    group = "DEFAULT_GROUP"
    addressWaitTime = "3000"
  }
  file {
    name = "file.conf"
  }
}

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

  nacos {
    serverAddr = "127.0.0.1:8848"
    namespace = "98d183cb-132e-4ae9-8f2d-bd2b758cd140"
    group = "DEFAULT_GROUP"
    #username = ""
    #password = ""
  }
  consul {
    serverAddr = "127.0.0.1:8500"
  }
  apollo {
    appId = "seata-server"
    apolloMeta = "http://192.168.1.204:8801"
    namespace = "application"
  }
  zk {
    serverAddr = "127.0.0.1:2181"
    sessionTimeout = 6000
    connectTimeout = 2000
    username = ""
    password = ""
  }
  etcd3 {
    serverAddr = "http://localhost:2379"
  }
  file {
    name = "file.conf"
  }
}

file.conf


## transaction log store, only used in seata-server
#这里手动加入service模块
service {
  #transaction service group mapping
  #修改,可不改,tx_group随便起名字。
  vgroupMapping.tx_group= "default"
  #only support when registry.type=file, please don't set multiple addresses
  # 此服务的地址
  default.grouplist = "127.0.0.1:8091"
  #disable seata
  disableGlobalTransaction = false
}

store {
  ## store mode: file、db、redis
  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
  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"
    url = "xxx"
    user = "xxx"
    password = "xxx"
    minConn = 5
    maxConn = 30
    globalTable = "global_table"
    branchTable = "branch_table"
    lockTable = "lock_table"
    queryLimit = 100
    maxWait = 5000
  }

  ## redis store property
  redis {
    host = "127.0.0.1"
    port = "6379"
    password = ""
    database = "0"
    minConn = 1
    maxConn = 10
    queryLimit = 100
  }

}

同步配置到nacos,使用方法 执行nacos_config.sh脚本 -h对应的是ip,-p对应的是端 -g对应nacos的group,-t对应nacos的namespace
./nacos_config.sh -h localhost -p 8848 -g DEFAULT_GROUP -t 98d183cb-132e-4ae9-8f2d-bd2b758cd140

#!/usr/bin/env bash
#  执行命令 ./nacos_config.sh -h localhost -p 8848 -g DEFAULT_GROUP -t 98d183cb-132e-4ae9-8f2d-bd2b758cd140
# 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.

while getopts ":h:p:g:t:u:w:" opt
do
  case $opt in
  h)
    host=$OPTARG
    ;;
  p)
    port=$OPTARG
    ;;
  g)
    group=$OPTARG
    ;;
  t)
    tenant=$OPTARG
    ;;
  u)
    username=$OPTARG
    ;;
  w)
    password=$OPTARG
    ;;
  ?)
    echo " USAGE OPTION: $0 [-h host] [-p port] [-g group] [-t tenant] [-u username] [-w password] "
    exit 1
    ;;
  esac
done

urlencode() {
  for ((i=0; i < ${#1}; i++))
  do
    char="${1:$i:1}"
    case $char in
    [a-zA-Z0-9.~_-]) printf $char ;;
    *) printf '%%%02X' "'$char" ;;
    esac
  done
}

if [[ -z ${host} ]]; then
    host=localhost
fi
if [[ -z ${port} ]]; then
    port=8848
fi
if [[ -z ${group} ]]; then
    group="SEATA_GROUP"
fi
if [[ -z ${tenant} ]]; then
    tenant=""
fi
if [[ -z ${username} ]]; then
    username=""
fi
if [[ -z ${password} ]]; then
    password=""
fi

nacosAddr=$host:$port
contentType="content-type:application/json;charset=UTF-8"

echo "set nacosAddr=$nacosAddr"
echo "set group=$group"

failCount=0
tempLog=$(mktemp -u)
function addConfig() {
  curl -X POST -H "${contentType}" "http://$nacosAddr/nacos/v1/cs/configs?dataId=$(urlencode $1)&group=$group&content=$(urlencode $2)&tenant=$tenant&username=$username&password=$password" >"${tempLog}" 2>/dev/null
  if [[ -z $(cat "${tempLog}") ]]; then
    echo " Please check the cluster status. "
    exit 1
  fi
  if [[ $(cat "${tempLog}") =~ "true" ]]; then
    echo "Set $1=$2 successfully "
  else
    echo "Set $1=$2 failure "
    (( failCount++ ))
  fi
}

count=0
for line in $(cat $(dirname "$PWD")/config.txt | sed s/[[:space:]]//g); do
  (( count++ ))
	key=${line%%=*}
    value=${line#*=}
	addConfig "${key}" "${value}"
done

echo "========================================================================="
echo " Complete initialization parameters,  total-count:$count ,  failure-count:$failCount "
echo "========================================================================="

if [[ ${failCount} -eq 0 ]]; then
	echo " Init nacos config finished, please start seata-server. "
else
	echo " init nacos config fail. "
fi

order客户端配置
首先maven引入seata依赖

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

order模块yaml文件加入seata配置

seata:
 enabled: true
 application-id: ${spring.application.name}-seata
 tx-service-group: tx_group
 enable-auto-data-source-proxy: false
 config:
   type: nacos
   nacos:
     namespace: ${spring.cloud.nacos.discovery.namespace}
     serverAddr: ${spring.cloud.nacos.discovery.server-addr}
     group: ${spring.cloud.nacos.discovery.group}
     #username: "nacos"
     #password: "nacos"
 registry:
   type: nacos
   nacos:
     application: seata-server
     server-addr: ${spring.cloud.nacos.discovery.server-addr}
     namespace: ${spring.cloud.nacos.discovery.namespace}
     group: ${spring.cloud.nacos.discovery.group}
     #username: "nacos"
     #password: "nacos"
 service:
   vgroupMapping:
     tx_group: default
   disable-global-transaction: false
   grouplist:
     default: 127.0.0.1:8091
 client:
   rm:
     # 是否上报一阶段成功
     report-success-enable: false

客户端pay配置

首先maven引入seata依赖

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

pay模块 yaml文件加入seata配置

seata:
  enabled: true
  application-id: ${spring.application.name}-seata
  tx-service-group: tx_group
  enable-auto-data-source-proxy: false
  config:
    type: nacos
    nacos:
      namespace: ${spring.cloud.nacos.discovery.namespace}
      serverAddr: ${spring.cloud.nacos.discovery.server-addr}
      group: ${spring.cloud.nacos.discovery.group}
      #username: "nacos"
      #password: "nacos"
  registry:
    type: nacos
    nacos:
      application: seata-server
      server-addr: ${spring.cloud.nacos.discovery.server-addr}
      namespace: ${spring.cloud.nacos.discovery.namespace}
      group: ${spring.cloud.nacos.discovery.group}
      #username: "nacos"
      #password: "nacos"
  service:
    vgroupMapping:
      tx_group: default
    disable-global-transaction: false
    grouplist:
      default: 127.0.0.1:8091
  client:
    rm:
      # 是否上报一阶段成功
      report-success-enable: false

客户端的seata.tx-service-group需要和服务端file.conf文件service.vgroupMapping.tx_group 名称一样
客户端的seata.service.vgroupMapping.tx_group的值需要和服务端file.conf文件service.vgroupMapping.tx_group的值一样

tx_group的名称自己可以随意定义,可以单个也可以用多个,这里我用单个

最后使用 @GlobalTransactional 即可使用分布式事务

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值