分布式事务中间件Seata+Springcloud+Mybatis

简介

Seata是基于AT模式设计出来的一套分布式事务中间件。2019 年 1 月,阿里巴巴中间件团队发起了开源项目 Fescar(Fast & EaSy Commit And Rollback)和社区一起共建开源分布式事务解决方案,后更名为Seata。它继承了XA和TCC的优点,以一种基本无代码入侵的方式,减轻分布式环境下事务的各种压力。

既然Seata是一个分布式事务的中间件,那么它就一定有服务端和客户端的概念。
摘取官方给的一张概念图,Seata一共有三个角色

  • TC,这里是seata服务端
  • TM,指的是我们的应用服务
  • RM,指的是数据库
    分布式事务中间件Seata+Springcloud+Mybatis_第1张图片

用一句话概括seata三个角色的作用,就是应用服务层的事务由seata管理,数据库的任何一个操作都会被seata拦截并记录,最终由seata统一提交或者回滚事务。

环境部署

  • seata-server-1.1.0
  • jdk1.8
  • springcloud2.0

技术要点

springcloud2+euraka+mybatis3+seata1.1.0

springcloud部署

这里主要讲seata的部署,springcloud的就不多做阐述了
注册中心使用eurea
一共启动三个服务
euraka-server,注册中心
orderApp,订单服务
StorageApp,库存服务

seata中间件部署

官网:http://seata.io/en-us/blog/download.html
github:https://github.com/seata/seata/releases

ps: 留意,笔者用的是1.1.0的版本
在这里插入图片描述
分布式事务中间件Seata+Springcloud+Mybatis_第2张图片

bin:二进制文件,主要是用于服务端启动
conf:配置文件
lib:依赖jar包(seata是有java编写的)

核心配置文件

编辑conf/registry.conf
这里我使用的注册中心是eureka,别名命名为seata-tc-server

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

  nacos {
    serverAddr = "localhost"
    namespace = ""
    cluster = "default"
  }
  eureka {
    serviceUrl = "http://localhost:8100/eureka"
    application = "seata-tc-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 = ""
    group = "SEATA_GROUP"
  }
  consul {
    serverAddr = "127.0.0.1:8500"
  }
  apollo {
    app.id = "seata-server"
    apollo.meta = "http://192.168.1.204:8801"
    namespace = "application"
  }
  zk {
    serverAddr = "127.0.0.1:2181"
    session.timeout = 6000
    connect.timeout = 2000
  }
  etcd3 {
    serverAddr = "http://localhost:2379"
  }
  file {
    name = "file.conf"
  }
}

配置中心选择以file文件方式,所以还需要修改conf/file.conf文件

transport {
  # tcp udt unix-domain-socket
  type = "TCP"
  #NIO NATIVE
  server = "NIO"
  #enable heartbeat
  heartbeat = true
  # the client batch send request enable
  enableClientBatchSendRequest = false
  #thread factory for netty
  threadFactory {
    bossThreadPrefix = "NettyBoss"
    workerThreadPrefix = "NettyServerNIOWorker"
    serverExecutorThreadPrefix = "NettyServerBizHandler"
    shareBossWorker = false
    clientSelectorThreadPrefix = "NettyClientSelector"
    clientSelectorThreadSize = 1
    clientWorkerThreadPrefix = "NettyClientWorkerThread"
    # netty boss thread size,will not be used for UDT
    bossThreadSize = 1
    #auto default pin or 8
    workerThreadSize = "default"
  }
  shutdown {
    # when destroy server, wait seconds
    wait = 3
  }
  serialization = "seata"
  compressor = "none"
}
# service configuration, only used in client side
service {
  #transaction service group mapping
  vgroupMapping.my_test_tx_group = "seata-tc-server"
  #only support when registry.type=file, please don't set multiple addresses
  default.grouplist = "127.0.0.1:8091"
  #degrade, current not support
  enableDegrade = false
  #disable seata
  disableGlobalTransaction = false
}
#client transaction configuration, only used in client side
client {
  rm {
    asyncCommitBufferLimit = 10000
    lock {
      retryInterval = 10
      retryTimes = 30
      retryPolicyBranchRollbackOnConflict = true
    }
    reportRetryCount = 5
    tableMetaCheckEnable = false
    reportSuccessEnable = false
    sqlParserType = druid
  }
  tm {
    commitRetryCount = 5
    rollbackRetryCount = 5
  }
  undo {
    dataValidation = true
    logSerialization = "jackson"
    logTable = "undo_log"
  }
  log {
    exceptionRate = 100
  }
}

## transaction log store, only used in server side
store {
  ## store mode: file、db
  mode = "file"
  ## 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) etc.
    datasource = "dbcp"
    ## mysql/oracle/h2/oceanbase etc.
    dbType = "mysql"
    driverClassName = "com.mysql.jdbc.Driver"
    url = "jdbc:mysql://127.0.0.1:3306/seata"
    user = "mysql"
    password = "mysql"
    minConn = 1
    maxConn = 10
    globalTable = "global_table"
    branchTable = "branch_table"
    lockTable = "lock_table"
    queryLimit = 100
  }
}
## server configuration, only used in server side
server {
  recovery {
    #schedule committing retry period in milliseconds
    committingRetryPeriod = 1000
    #schedule asyn committing retry period in milliseconds
    asynCommittingRetryPeriod = 1000
    #schedule rollbacking retry period in milliseconds
    rollbackingRetryPeriod = 1000
    #schedule timeout retry period in milliseconds
    timeoutRetryPeriod = 1000
  }
  undo {
    logSaveDays = 7
    #schedule delete expired undo_log in milliseconds
    logDeletePeriod = 86400000
  }
  #unit ms,s,m,h,d represents milliseconds, seconds, minutes, hours, days, default permanent
  maxCommitRetryTimeout = "-1"
  maxRollbackRetryTimeout = "-1"
  rollbackRetryTimeoutUnlockEnable = false
}

## metrics configuration, only used in server side
metrics {
  enabled = false
  registryType = "compact"
  # multi exporters use comma divided
  exporterList = "prometheus"
  exporterPrometheusPort = 9898
}

其中,要设置好事务组映射关系
笔者的配置为vgroupMapping.my_test_tx_group = “seata-tc-server”
表示:若配置了事务组"my_test_tx_group",则会去注册中心找别名为seata-tc-server的服务

配置完成后执行bin/seata-server.bat(window)或者bin/seata-server.sh(linux),seata默认端口8091

微服务配置(订单、库存)

pom依赖


<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
dependency>


<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
    <groupId>org.mybatis.spring.bootgroupId>
    <artifactId>mybatis-spring-boot-starterartifactId>
    <version>1.3.1version>
dependency>


<dependency>
    <groupId>com.alibaba.cloudgroupId>
    <artifactId>spring-cloud-starter-alibaba-seataartifactId>
    <version>2.1.0.RELEASEversion>
    <exclusions>
        <exclusion>
            <groupId>io.seatagroupId>
            <artifactId>seata-allartifactId>
        exclusion>
    exclusions>
dependency>
<dependency>
    <groupId>io.seatagroupId>
    <artifactId>seata-allartifactId>
    <version>1.1.0version>
dependency>

application.yml配置

server:
  port: 8901
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:8100/eureka/
spring:
  application:
    name: app-storage
  datasource:
    url: jdbc:mysql://bigdata-pro01.kfk.com:3306/winnie?characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false&useSSL=true
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
  cloud:
    alibaba:
      seata:
        tx-service-group: my_test_tx_group # 使用seata管理分布式事务,指定事务组
mybatis:
  configuration:
    map-underscore-to-camel-case: true
  type-aliases-package: com.winnie.mapper

在resources目录添加两个配置文件

file.conf
registry.conf
这两个文件来自seata的配置文件,从上述seata直接拷贝过来

配置数据源代理类

seata的三个角色之一RM,就是通过代理类去拦截sql执行的。因为这里使用的是mybatis,mybatis底层使用的是SqlSessionFactory,所以我们需要在SqlSessionFactory之前把数据源重新包装一下,上代码瞧瞧便知

/**
 * seata所需代理数据的配置类
 */
@Configuration
public class SeataDataSourceProxyConfig {
    /**
     * 因为orm使用的是mybatis,所以需要在orm执行前被seata代理
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean
    public SqlSessionFactory dataSourceProxy(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(new DataSourceProxy(dataSource));
        return sqlSessionFactoryBean.getObject();
    }
}

使用@GlobalTranscational注解

订单服务

@PostMapping("insertOne")
@ApiOperation("创建订单")
@GlobalTransactional(rollbackFor = Exception.class)
public ResponseEntity insertOne(OrderEntity orderEntity){
    ResponseEntity responseEntity;
    // 1. 下单
    try {
        orderEntity.setCreateTime(new Date());
        orderMapper.insertOne(orderEntity);
        // 2. 减库存
        responseEntity = storageServiceFeign.deCount(orderEntity.getGoodsid(), 1);
    } catch (Exception e) {
        throw  new RuntimeException("服务异常,事务回滚");
    }
    return responseEntity;
}

库存服务

@GlobalTransactional(rollbackFor = Exception.class)
@PostMapping("/deCount")
public ResponseEntity deCount(String goodsid, Integer count) {
    Long result = storageMapper.updateCount(goodsid, count);
    if (result <= 0) {
        throw new RuntimeException("更新失败");
    }
    return ResponseEntity.success("更新成功");
}

创建undo log表

seata拦截sql后,会存储在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;

测试

创建订单时,对应商品的库存-1。
若创建订单时,库存没有正常-1,则事务失败,订单不会被创建。

你可能感兴趣的:(java,mysql,分布式,中间件,mybatis)