SpringCloud整合Nacos + Seata 示例(kotlin)

1 篇文章 0 订阅
1 篇文章 0 订阅

前言

​ seata属于近几年开源的项目,在官网大多只详细介绍了分布式事务概念及其标准实现原理,对于实践的代码少之又少,由于seata的版本更新以及与spring的整合,再加上seata配置的多样性和灵活性,各大论坛配置也是五花八门,所以很难搭建成功,题主几乎已经是在各大搜索引擎遍历了seata的搭建版本,有这么写的,有那么写的,能这么配置的,还能那么配置的,还有缺少文件什么的,真心搞得心态爆炸,可seata这么好的开源项目,到公司后你不得成为首选,所以题主在心态一次又一次炸裂后,在大学毕业前准备总结了一套SpringCloud整合Nacos + Seata 的kotlin版的示例(推荐搭建使用kotlin搭建)。

​ 独立学习是一件既快乐又痛苦的事情:痛苦 -> 痛苦 -> 痛苦 -> 痛苦 -> 快乐 -> 痛苦 -> … 痛苦 -> 快乐 - v - 。

分布式事务基础

seata介绍

Seata 是一款开源的分布式事务解决方案,致力于在微服务架构下提供高性能和简单易用的分布式事务服务。

分布式事务

分布式事务顾名思义就是要在分布式系统中实现事务,它其实是由多个本地事务组合而成。

分布式事务是指事务的参与者支持事务的服务器资源服务器以及事务管理器分别位于不同的分布式系统的不同节点之上。

对于分布式事务而言几乎满足不了 ACID,其实对于单机事务而言大部分情况下也没有满足 ACID。

准备工具

seata1.4.0

下载地址:https://github.com/seata/seata/releases

seata-develop

下载地址:https://github.com/seata/seata

Nacos1.2.1

下载地址:https://github.com/alibaba/nacos/releases

简单配置

nacos配置

​ 解压nacos二进制压缩包,为了将nacos的配置进行持久化,我们选择将配置中心的存储方式更改为msyql存储

  • 在数据库新建nacos_config数据库,在conf目录下将找到nacos-mysql.sql文件并执行该sql文件。

  • 在application.properties修改为如下配置,账号密码填自己的。

    #*************** Config Module Related Configurations ***************#
    ### If user MySQL as datasource:
    spring.datasource.platform=mysql    
    
    ### Count of DB:
    db.num=1
    
    ### Connect URL of DB:
    db.url.0=jdbc:mysql://localhost:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
    db.user=root
    db.password=root
    

现在我们的nacos已经将配置持久到数据库了

seata配置

​ 解压seata-develop压缩包和seata压缩包:

  • 在seata-develop解压后的script\config-center目录下将config.txt复制到seata解压后的根目录。
  • 在seata-develop解压后的script\config-center\nacos目录下将这两个文件复制到seata解压后的conf目录
  • 在seata的conf目录下打开shell窗口执行: sh nacos-config.sh hostip

新建nacos_seata数据库,执行如下sql脚本:

-- -------------------------------- The script used when storeMode is 'db' --------------------------------
-- the table to store GlobalSession data
CREATE TABLE IF NOT EXISTS `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
  DEFAULT CHARSET = utf8;

-- the table to store BranchSession data
CREATE TABLE IF NOT EXISTS `branch_table`
(
    `branch_id`         BIGINT       NOT NULL,
    `xid`               VARCHAR(128) NOT NULL,
    `transaction_id`    BIGINT,
    `resource_group_id` VARCHAR(32),
    `resource_id`       VARCHAR(256),
    `branch_type`       VARCHAR(8),
    `status`            TINYINT,
    `client_id`         VARCHAR(64),
    `application_data`  VARCHAR(2000),
    `gmt_create`        DATETIME(6),
    `gmt_modified`      DATETIME(6),
    PRIMARY KEY (`branch_id`),
    KEY `idx_xid` (`xid`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

-- the table to store lock data
CREATE TABLE IF NOT EXISTS `lock_table`
(
    `row_key`        VARCHAR(128) NOT NULL,
    `xid`            VARCHAR(96),
    `transaction_id` BIGINT,
    `branch_id`      BIGINT       NOT NULL,
    `resource_id`    VARCHAR(256),
    `table_name`     VARCHAR(32),
    `pk`             VARCHAR(36),
    `gmt_create`     DATETIME,
    `gmt_modified`   DATETIME,
    PRIMARY KEY (`row_key`),
    KEY `idx_branch_id` (`branch_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

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;

配置conf下file.conf文件:

## transaction log store, only used in seata-server
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.jdbc.Driver"
    url = "jdbc:mysql://127.0.0.1:3306/nacos_seata"     
    user = "lishuang"   
    password = "jiayou0000"
    minConn = 5
    maxConn = 100
    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
    maxTotal = 100
    queryLimit = 100
  }

}

配置conf下registry.conf文件

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "nacos"   			 #更改注册中心为nacos
  loadBalance = "RandomLoadBalance"
  loadBalanceVirtualNodes = 10

  nacos {
    application = "seata-server"
    serverAddr = "127.0.0.1:8848"
    group = "SEATA_GROUP"
    namespace = ""
    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 = "SEATA_GROUP"
    addressWaitTime = "3000"
  }
  file {
    name = "file.conf"
  }
}

config {
  # file、nacos 、apollo、zk、consul、etcd3
  type = "nacos"       #更改配置中心为nacos

  nacos {
    serverAddr = "127.0.0.1:8848"
    namespace = ""
    group = "SEATA_GROUP"
    username = ""
    password = ""
  }
  consul {
    serverAddr = "127.0.0.1:8500"
  }
  apollo {
    appId = "seata-server"
    apolloMeta = "http://192.168.1.204:8801"
    namespace = "application"
    apolloAccesskeySecret = ""
  }
  zk {
    serverAddr = "127.0.0.1:2181"
    sessionTimeout = 6000
    connectTimeout = 2000
    username = ""
    password = ""
  }
  etcd3 {
    serverAddr = "http://localhost:2379"
  }
  file {
    name = "file.conf"
  }
}

服务启动

  • cmd运行seata bin目录下的seata-server.bat
  • cmd运行nacos bin目录下的startup.cmd

登录nacos:http://ip:8848/nacos/index.html ,默认账户密码都是:nacos,登录进去打开配置列表可以看到近50条配置记录,如果没有配置记录,请返回至 sh nacos-config.sh hostip 这一步!!!

在服务列表会看到名为 seata-server 已经注册到nacos。

项目配置

父工程管理依赖,pom.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.jiayou</groupId>
    <artifactId>nacos-seata</artifactId>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>seata-consumer</module>
        <module>seata-provider1</module>
        <module>seata-provider2</module>
    </modules>

    <packaging>pom</packaging>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-stdlib-jdk8 -->
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-stdlib-jdk8</artifactId>
            <version>1.4.10</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-reflect -->
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-reflect</artifactId>
            <version>1.4.10</version>
            <scope>runtime</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.seata/seata-spring-boot-starter -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
            <version>2.2.1.RELEASE</version>
            <exclusions>
                <exclusion>
                    <groupId>io.seata</groupId>
                    <artifactId>seata-spring-boot-starter</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.seata</groupId>
            <artifactId>seata-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.jetbrains.kotlin</groupId>
                <artifactId>kotlin-maven-plugin</artifactId>
                <version>1.4.10</version>
                <executions>
                    <execution>
                        <id>compile</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>


    <dependencyManagement>
        <dependencies>
            <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-dependencies -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.2.1.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-dependencies -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <!-- https://mvnrepository.com/artifact/com.alibaba.cloud/spring-cloud-alibaba-dependencies -->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.2.1.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

三个子项目我们会引入:

  <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba.cloud/spring-cloud-starter-alibaba-nacos-discovery -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>

seata-provider1服务提供者

服务接口
@EnableFeignClients
@RestController
@EnableDiscoveryClient
@SpringBootApplication
open class SeataProvider8001Applciation {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            runApplication<SeataProvider8001Applciation>(*args)
        }
    }
    
    @Autowired
    private lateinit var jdbcTemplate: JdbcTemplate

    @RequestMapping("save1")
    open fun save1() {
        jdbcTemplate.update("insert into user1 values(1,'lishuang',100)")
        println("Provider8001 -> 保存成功")
    }
    
}
application.yml
server:
  port: 8001

spring:
  application:
    name: seata-provider8001
  cloud:
    nacos:
      server-addr: localhost:8848
    alibaba:
      seata:
        tx-service-group: kotlin_group   #事务组
  datasource:
    url: jdbc:mysql://localhost:3306/nacos_seata?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver # 3.2.0开始支持SPI可省略此配置

feign:
  hystrix:
    enabled: false

seata:
  enabled: true
  application-id: applicationName1
  tx-service-group: kotlin_group      #事务组
  enable-auto-data-source-proxy: true
  config:
    type: nacos
    nacos:
      namespace:
      serverAddr: 127.0.0.1:8848
      group: SEATA_GROUP
      username: "nacos"
      password: "nacos"
  registry:
    type: nacos
    nacos:
      application: seata-server
      server-addr: 127.0.0.1:8848
      group: SEATA_GROUP
      namespace:
      username: "nacos"
      password: "nacos"

seata-provide2服务提供者

服务接口
@RestController
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
open class SeataProvider8002Applciation {

    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            runApplication<SeataProvider8002Applciation>(*args)
        }
    }

    @Autowired
    private lateinit var jdbcTemplate: JdbcTemplate


    @RequestMapping("save2")
    open fun save2(@RequestParam("id") id: Int) {
        if (id == 0)
            1 / 0
        jdbcTemplate.update("insert into user2 values(1,'lishuang',100)")
        println("Provider8002 -> 保存成功")
    }

}
application.yml
server:
  port: 8002

spring:
  application:
    name: seata-provider8002
  cloud:
    nacos:
      server-addr: localhost:8848
    alibaba:
      seata:
        tx-service-group: kotlin_group   #事务组
  datasource:
    url: jdbc:mysql://localhost:3306/nacos_seata?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver # 3.2.0开始支持SPI可省略此配置

feign:
  hystrix:
    enabled: false

seata:
  enabled: true
  application-id: applicationName2
  tx-service-group: kotlin_group   #事务组
  enable-auto-data-source-proxy: true
  config:
    type: nacos
    nacos:
      namespace:
      serverAddr: 127.0.0.1:8848
      group: SEATA_GROUP
      username: "nacos"
      password: "nacos"
  registry:
    type: nacos
    nacos:
      application: seata-server
      server-addr: 127.0.0.1:8848
      group: SEATA_GROUP
      namespace:
      username: "nacos"
      password: "nacos"

seata-consumer服务消费者

feign接口声明
@FeignClient("seata-provider8001")
@Component
interface Api1 {
    @RequestMapping("save1")
    fun save1()
}


@FeignClient("seata-provider8002")
@Component
interface Api2 {
    @RequestMapping("save2")
    fun save2(@RequestParam("id") id: Int)
}
服务接口
@EnableFeignClients
@RestController
@EnableDiscoveryClient
@SpringBootApplication
open class SeataConsumerApplciation {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            runApplication<SeataConsumerApplciation>(*args)
        }
    }

    @Autowired
    private lateinit var api1: Api1      

    @Autowired
    private lateinit var api2: Api2


    @RequestMapping("/save1")          //未开启分布式事务,seata-provider1插入成功,seata-provider2插入失败
    open fun save1() {				   //该分布式事务无人治理,所以并不会回滚
        api1.save1()
        api2.save2(0)
        println("保存成功!")
    }


    @GlobalTransactional				//开启分布式事务,seata-provider1插入成功,seata-provider2插入失败
    @RequestMapping("/save2")		    //该分布式事务由seata事务管理器代理,在seata-provider2服务异常后会seata记录下失败的操作记录
    open fun save2() {					//在seata事务管理器和事务参与者们投票,有任何一个参与者异常都会导致整个分布式事务回滚
        api1.save1()
        api2.save2(0)
        println("保存成功!")
    }


    @GlobalTransactional				//开启分布式事务,seata-provider1插入成功,seata-provider2插入成功				
    @RequestMapping("/save3")		    //该分布式事务由seata事务管理器代理
    open fun save3() {					//在seata事务管理器和事务参与者们投票,没有异常发生,通知各个事务参与者们提交事务
        api1.save1()
        api2.save2(1)
        println("保存成功!")
    }

}
application.yml
server:
  port: 8088

spring:
  application:
    name: seata-consumer
  cloud:
    nacos:
      server-addr: localhost:8848
    alibaba:
      seata:
        tx-service-group: kotlin_group   #事务组

feign:
  hystrix:
    enabled: false


seata:
  enabled: true
  application-id: applicationNameServer
  tx-service-group: kotlin_group   #事务组
  enable-auto-data-source-proxy: true
  config:
    type: nacos
    nacos:
      namespace:
      serverAddr: 127.0.0.1:8848
      group: SEATA_GROUP
      username: "nacos"
      password: "nacos"
  registry:
    type: nacos
    nacos:
      application: seata-server
      server-addr: 127.0.0.1:8848
      group: SEATA_GROUP
      namespace:
      username: "nacos"
      password: "nacos"
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值