SpringCloud integrates Nacos + Seata study notes

SpringCloud integrates Nacos + Seata study notes

1. seata1.4.1 configuration

1. seata-server download

Link: github seata download .
Download seata1.4.1, put the zip package in the corresponding place, and decompress it directly.

2. Modify the file.conf and registry.conf configuration files of seata1.4.1

2.1. Connect to Oracle database configuration

file.conf配置文件

store {
  ## store mode: file、db、redis
  mode = "db"

  ## database store property
  db {
    ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp) etc.
    datasource = "druid"
    ## mysql/oracle/postgresql/h2/oceanbase etc.
    dbType = "oracle"
    driverClassName = "oracle.jdbc.driver.OracleDriver"
    url = "jdbc:oracle:thin:localhost:1521:ORCL"
    user = "***"
    password = "***"
    minConn = 5
    maxConn = 100
    globalTable = "GLOBAL_TABLE"
    branchTable = "BRANCH_TABLE"
    lockTable = "LOCK_TABLE"
    queryLimit = 100
    maxWait = 5000
  }

registry.conf配置文件

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "nacos"
  loadBalance = "RandomLoadBalance"
  loadBalanceVirtualNodes = 10

  nacos {
    application = "seata-server"
    serverAddr = "127.0.0.1:8848"
    group = "SEATA_GROUP"
    namespace = ""
    cluster = "default"
    username = "nacos"
    password = "nacos"
  }
}

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

  nacos {
    serverAddr = "127.0.0.1:8848"
    namespace = ""
    group = "SEATA_GROUP"
    username = "nacos"
    password = "nacos"
  }
}

2.2. Connect to MySQL database configuration

file.conf配置文件

store {
  ## store mode: file、db、redis
  mode = "db"

  ## database store property
	db {
    ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp) etc.
    datasource = "druid"
    ## mysql/oracle/postgresql/h2/oceanbase etc.
    dbType = "mysql"
    driverClassName = "com.mysql.jdbc.Driver"
    url = "jdbc:mysql://127.0.0.1:3306/seata"
    user = "***"
    password = "***"
    minConn = 5
    maxConn = 30
    globalTable = "global_table"
    branchTable = "branch_table"
    lockTable = "lock_table"
    queryLimit = 100
  }
}

registry.conf配置文件

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "nacos"
  loadBalance = "RandomLoadBalance"
  loadBalanceVirtualNodes = 10

  nacos {
    application = "seata-server"
    serverAddr = "127.0.0.1:8848"
    group = "SEATA_GROUP"
    namespace = ""
    cluster = "default"
    username = "nacos"
    password = "nacos"
  }
}

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

  nacos {
    serverAddr = "127.0.0.1:8848"
    namespace = ""
    group = "SEATA_GROUP"
    username = "nacos"
    password = "nacos"
  }
}

3. Add the oracle driver package to the lib directory of the seata installation directory.

Seata is connected to MySQL by default. If it is a MySQL database connection, there is no need to import the package; but there is no Oracle installation driver. If you want to use the Oracle database for data connection, you need to import the Oracle driver package. What I imported here is oracle6.jar.

4. Database table creation

4.1. Oracle database table creation

1、新建表 UNDO_LOG、GLOBAL_TABLE、BRANCH_TABLE、LOCK_TABLE
-- Create table
create table UNDO_LOG
(
  id            NUMBER(20) not null,
  branch_id     NUMBER(20) not null,
  xid           VARCHAR2(100) not null,
  context       VARCHAR2(128) not null,
  rollback_info BLOB,
  log_status    INTEGER,
  log_created   DATE,
  log_modified  DATE
);
-- Create/Recreate indexes 
create index IDX_XRID on UNDO_LOG (BRANCH_ID, XID);
-- Create/Recreate primary, unique and foreign key constraints 
alter table UNDO_LOG
  add constraint PK_UNDO primary key (ID);
create sequence UNDO_LOG_SEQ
minvalue 1
maxvalue 9999999999999999999999999
start with 1
increment by 1
cache 20;

create table GLOBAL_TABLE (
  xid varchar2(128)  not null,
  transaction_id NUMBER(20),
  status NUMBER(10) not null,
  application_id varchar2(64),
  transaction_service_group varchar2(64),
  transaction_name varchar2(128),
  timeout NUMBER(10),
  begin_time NUMBER(20),
  application_data varchar2(2000),
  gmt_create DATE,
  gmt_modified DATE
);

create table BRANCH_TABLE (
  branch_id NUMBER(20) not null,
  xid varchar2(128) not null,
  transaction_id NUMBER(20) ,
  resource_group_id varchar2(128),
  resource_id varchar2(256) ,
  lock_key varchar2(256) ,
  branch_type varchar2(8) ,
  status NUMBER(10),
  client_id varchar2(64),
  application_data varchar2(2000),
  gmt_create DATE,
  gmt_modified DATE
);

create table LOCK_TABLE (
  row_key varchar2(128) not null,
  xid varchar2(128),
  transaction_id NUMBER(20) ,
  branch_id NUMBER(20),
  resource_id varchar2(256) ,
  table_name varchar2(64) ,
  pk varchar2(128) ,
  gmt_create DATE ,
  gmt_modified DATE
);

4.2. Create MySQL database table

-- MySQL 数据库新建库 seata,在seata库中新建三张表
-- 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`)
);

After configuring these, you are only one step away from success. Next, start the nacos service. After starting, start the seata service. Then you will find that the seata-service service will be found in the nacos service. As shown in the picture: Insert image description here
The next step is to integrate it into your own project.

2. springboot project integration

1. Introduce dependencies into the pom.xml file

pom.xml 依赖引入

<dependencies>
   <dependency>
       <groupId>io.seata</groupId>
       <artifactId>seata-spring-boot-starter</artifactId>
       <version>1.4.1</version>
   </dependency>
</dependencies>

2. Configure application.yaml

application.yaml

server:
  port: 9999
spring:
  profiles:
    active: dev

3. Configure bootstrap.properties

bootstrap.properties

spring.application.name=demo-test
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.cloud.nacos.config.file-extension=yaml

4. Open the configuration file of the nacos configuration project

Add seata connection information, etc.yaml

#seata 配置, 代替file.conf和registry.conf配置
seata:
  enabled: true
  # 事务群组(可以每个应用独立取名,也可以使用相同的名字)
  tx-service-group: my_test_tx_group
  client:
    rm-report-success-enable: true
    # 异步提交缓存队列长度(默认10000)
    rm-async-commit-buffer-limit: 1000
      # 一阶段全局提交结果上报TC重试次数(默认1次,建议大于1)
    tm-commit-retry-count: 3
      # 一阶段全局回滚结果上报TC重试次数(默认1次,建议大于1)
    tm-rollback-retry-count: 3
    support:
      # 数据源自动代理开关(默认false关闭)
      spring-datasource-autoproxy: true
    service:
      vgroup-mapping:
        # TC 集群(必须与seata-server保持一致)
        my_test_tx_group: seata
      # grouplist配置不生效,不需要配置,只要将seata注册到相同的eureka即可
      grouplist:
        default: 127.0.0.1:8095
  application-id: demo-teat
  registry:
    type: nacos
    nacos:
      server-addr: 127.0.0.1:8848

5. Use

@GlobalTransactional

6. Start the project for testing

test seata.

package com.example.demo.contraller;

import com.example.demo.pojo.Commodity;
import com.example.demo.service.CommodityService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/demo/commodity",produces = "application/json;charset=UTF-8")
public class CommodityContraller {
    
    

    @Autowired
    private CommodityService commodityService;

    @GlobalTransactional
    @GetMapping(value = "/updateCommodity")
    public String UpdateCommodity(@RequestParam(value = "id") Integer id, @RequestParam(value = "num") Integer num){
    
    
        Commodity commodity = new Commodity();
        commodity.setId(id);
        commodity.setNum(num);
        Integer integer = commodityService.updateCommodity(commodity);

        System.out.println(integer);

        //int i = 10/0;

        return Integer.toString(integer);
    }

    @GetMapping(value = "/test")
    public String test(){
    
    
        return "hello wrold!";
    }
}

Seata distributed transactions either succeed together or fail together, and must be a holistic transaction.

Guess you like

Origin blog.csdn.net/qq_45745778/article/details/115869840