阿里雲分佈式事務seata:springcloud-eureka-feign-mybatis

springcloud-eureka-feign-mybatis-seata-client/server

注:來源阿里雲開源seata,本人只做修改

概覽:seata由服務端及客戶端組成,服務端是阿里的項目需要在後臺一直運行,客戶端只是集成了客戶端部分配置文件而已。需要兩端同時運行纔可以完成分佈式事務;

服務端:https://github.com/xieshenace/springcloud-eureka-feign-mybatis-seata-server

客戶端:https://github.com/xieshenace/springcloud-eureka-feign-mybatis-seata-client

1.整合seata的demo,此demo都配置好了,拉下來按照步驟,直接可以跑起來觀察效果。

2.demo項目整合Seata,主要步驟如下:(可參考進行自己項目整合)

  • 1.下載服務端:原:下載seata-server,放到linux或者自己的window/mac中;
  • 2.下載客戶端:此Demo項目(引入配置文件,修改配置文件(注意不要遺漏,可參考下方几個關鍵步驟))
  • 3.數據源代理設置
  • 4.創建數據庫表
  • 5.啓動eureka,啓動server,啓動client(自己的服務比如訂單啊,倉庫啊,等等等)

關於調用成環和seata-server HA,見最後部分

1.此demo技術選型及版本信息

註冊中心:eureka

服務間調用:feign

持久層:mybatis 

數據庫:mysql 5.7.20

Springboot:2.1.7.RELEASE

Springcloud:Greenwich.SR2

jdk:1.8 

seata:1.1

使用不同組件,配置情況不同,可參考其他sample(開源地址:https://github.com/seata/seata-samples);

2.demo概況

demo分爲四個項目,單獨啓動。

  • eureka:作爲註冊中心
  • order:訂單服務,用戶下單後,會創建一個訂單添加在order數據庫,同時會扣減庫存storage,扣減賬戶account;
  • storage:庫存服務,用戶扣減庫存;
  • account:賬戶服務,用於扣減賬戶餘額;

order服務關鍵代碼如下:

  /**
   * 創建訂單
   *
   * @param order
   * @return 測試結果: 1.添加本地事務:僅僅扣減庫存 2.不添加本地事務:創建訂單,扣減庫存
   */
  @Override
  @GlobalTransactional(name = "fsp-create-order", rollbackFor = Exception.class)
  public void create(Order order) {
    LOGGER.info("------->交易開始");
    // 本地方法
    orderDao.create(order);
    // 遠程方法 扣減庫存
    storageApi.decrease(order.getProductId(), order.getCount());
    // 模擬異常情況
    // int i = 1 / 0;
    // 遠程方法 扣減賬戶餘額
    LOGGER.info("------->扣減賬戶開始order中");
    accountApi.decrease(order.getUserId(), order.getMoney());
    LOGGER.info("------->扣減賬戶結束order中");

    LOGGER.info("------->交易結束");
  }

3.使用步驟

  • 1.拉取本客戶端demo代碼 git clone xxxx;
  • 2.下載seata-server;
  • 3.執行本demo每個項目下的建表語句,resource下xx.sql文件;(undo_log.sql、account.sql、order.sql、storage.sql);
    注:undo_log.sql需要在項目每個庫都需要有一個。如果項目用的一個庫則需要一個表就行;
  • 4.seata相關建表語句見下文說明;

4.seata server(服務端)端配置信息修改

seata-server中,/conf目錄下,有兩個配置文件,需要結合自己的情況來修改:

1.file.conf

裏面有事務組配置,鎖配置,事務日誌存儲等相關配置信息,由於此demo使用db存儲事務信息,我們這裏要修改store中的配置:

## **原本配置**:
## transaction log store
store {
  ## store mode: file、db
  mode = "db"   修改這裏,表明事務信息用db存儲

  ## file store 當mode=db時,此部分配置就不生效了,這是mode=file的配置
  file {
    dir = "sessionStore"

    # branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions
    max-branch-session-size = 16384
    # globe session size , if exceeded throws exceptions
    max-global-session-size = 512
    # file buffer size , if exceeded allocate new buffer
    file-write-buffer-cache-size = 16384
    # when recover batch read size
    session.reload.read_size = 100
    # async, sync
    flush-disk-mode = async
  }

  ## database store  mode=db時,事務日誌存儲會存儲在這個配置的數據庫裏
  db {
    ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp) etc.
    datasource = "dbcp"
    ## mysql/oracle/h2/oceanbase etc.
    db-type = "mysql"
    driver-class-name = "com.mysql.jdbc.Driver"
    url = "jdbc:mysql://116.62.62.26/seat-server"  修改這裏
    user = "root"  修改這裏
    password = "root"  修改這裏
    min-conn = 1
    max-conn = 3
    global.table = "global_table"
    branch.table = "branch_table"
    lock-table = "lock_table"
    query-limit = 100
  }
}

如果mode類型中選擇的是db模式則:
由於此demo我們使用db模式存儲事務日誌,所以,我們要創建三張表:global_table,branch_table,lock_table,建表sql在上面下載的seata-server的/conf/db_store.sql中;

由於存儲undo_log是在業務庫中,所以在每個業務庫中,還要創建undo_log表,建表sql在/conf/db_undo_log.sql中。

由於我自定義了事務組名稱,所以這裏也做了修改:

service {
  #vgroup->rgroup
  vgroup_mapping.fsp_tx_group = "default"  修改這裏,fsp_tx_group這個事務組名稱是我自定義的,一定要與client端的這個配置一致!否則會報錯!
  #only support single node
  default.grouplist = "127.0.0.1:8091"   此配置作用參考:https://blog.csdn.net/weixin_39800144/article/details/100726116
  #degrade current not support
  enableDegrade = false
  #disable
  disable = false
  #unit ms,s,m,h,d represents milliseconds, seconds, minutes, hours, days, default permanent
  max.commit.retry.timeout = "-1"
  max.rollback.retry.timeout = "-1"
}

其他的可以先使用默認值。
如果,和本demo服務端一致使用的是file模式,則不需要做上面操作,直接使用本Demo服務端配置

## **本Demo服務端file.conf 配置**:
## transaction log store, only used in seata-server
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
  }
}

2.registry.conf

registry{}中是註冊中心相關配置,config{}中是配置中心相關配置。seata中,註冊中心和配置中心是分開實現的,是兩個東西。

我們這裏用eureka作註冊中心,所以,只用修改registry{}中的:

## **原本配置**:
registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "eureka"  修改這裏,指明註冊中心使用什麼

  nacos {
    serverAddr = "localhost"
    namespace = ""
    cluster = "default"
  }
  eureka {
    serviceUrl = "http://localhost:8761/eureka"  修改這裏註冊中心地址
    application = "default"  
    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"
  }
}

其他的配置可以暫時使用默認值。


## **本demo服務端registry.conf配置**:
registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "eureka"
  eureka {
    serviceUrl = "http://localhost:8761/eureka"
    application = "default"
    weight = "1"
  }
}

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

  file {
    name = "file.conf"
  }
}

現在已經完成配置修改了,等eureka啓動後,就可以啓動seata-server了:
如果是在windows下啓動seata-server:執行/bin/seata-server.bat即可;
如果是在mac/linux下啓動seata-server:sh /bin/seata-server.sh即可;

5.client本Demo(自己項目)端相關配置

1.普通配置

client端的幾個服務,都是普通的springboot整合了springCloud組件的正常服務,所以,你需要配置eureka,數據庫,mapper掃描等,即使不使用seata,你也需要做,這裏不做特殊說明,看代碼就好。

2.特殊配置

1.application.yml

以order服務爲例,除了常規配置外,這裏還要配置下事務組信息:(每個需要分佈式的項目中都需要這個,所以都需要配置)

spring:
    application:
        name: order-server
    cloud:
        alibaba:
            seata:
                tx-service-group: fsp_tx_group  
##這個fsp_tx_group自定義命名很重要,server,client都要保持一致

2.file.conf

注意:file.conf、registry.conf每個需要分佈式事務的項目中都要有這兩個文件,修改好之後直接複製就可以
主要是修改下面:fsp_tx_group 這個名字爲自己改的那個名字,要保持統一;

transport {
  # tcp udt unix-domain-socket
  type = "TCP"
  #NIO NATIVE
  server = "NIO"
  #enable heartbeat
  heartbeat = true
  # the client batch send request enable
  enableClientBatchSendRequest = true
  #thread factory for netty
  threadFactory {
    bossThreadPrefix = "NettyBoss"
    workerThreadPrefix = "NettyServerNIOWorker"
    serverExecutorThread-prefix = "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 {
  #transaction service group mapping
  
  ########注要是修改fsp_tx_group這個名字############
  vgroupMapping.fsp_tx_group = "default"
  #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 {
  rm {
    asyncCommitBufferLimit = 10000
    lock {
      retryInterval = 10
      retryTimes = 30
      retryPolicyBranchRollbackOnConflict = true
    }
    reportRetryCount = 5
    tableMetaCheckEnable = false
    reportSuccessEnable = false
  }
  tm {
    commitRetryCount = 5
    rollbackRetryCount = 5
  }
  undo {
    dataValidation = true
    logSerialization = "jackson"
    logTable = "undo_log"
  }
  log {
    exceptionRate = 100
  }
}

3.registry.conf

使用eureka做註冊中心,僅需要修改eureka的配置即可:

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

  eureka {
    serviceUrl = "http://localhost:8761/eureka"
    application = "default"
    weight = "1"
  }
}

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

  file {
    name = "file.conf"
  }
}

其他的使用默認值就好。

3.數據源代理

這個是要特別注意的地方,seata對數據源做了代理和接管,在每個參與分佈式事務的服務中,都要做如下配置:

/**
 * 數據源代理
 * @author wangzhongxiang
 */
@Configuration
public class DataSourceConfiguration {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        return druidDataSource;
    }

    @Primary
    @Bean("dataSource")
    public DataSourceProxy dataSource(DataSource druidDataSource){
        return new DataSourceProxy(druidDataSource);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy)throws Exception{
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSourceProxy);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
        .getResources("classpath*:/mapper/*.xml"));
        sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
        return sqlSessionFactoryBean.getObject();
    }

}

以及:每個分佈式事務的啓動類都需要加註解(@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)):比如

/**
 * 訂單服務
 * @author wangzhongxiang
 */
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@MapperScan("io.seata.sample.dao")
@EnableDiscoveryClient
@EnableFeignClients
public class OrderServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderServerApplication.class, args);
    }
}

6.啓動測試

然後可以模擬正常情況,異常情況,超時情況等,觀察數據庫即可。

這個demo,未做各種優化,如果壓測,需要修改和優化一些配置,壓測出錯了,不一定是seata的鍋,自己先排查,再去羣裏問問。

7.日誌

正常情況:

1.order

2019-09-06 15:44:33.536  INFO 53904 --- [io-8080-exec-10] i.seata.tm.api.DefaultGlobalTransaction  : Begin new global transaction [192.168.158.133:8091:2021468859]
2019-09-06 15:44:33.536  INFO 53904 --- [io-8080-exec-10] c.j.order.service.OrderServiceImpl       : ------->交易開始
2019-09-06 15:44:34.376  INFO 53904 --- [io-8080-exec-10] c.j.order.service.OrderServiceImpl       : ------->交易結束
2019-09-06 15:44:34.593  INFO 53904 --- [io-8080-exec-10] i.seata.tm.api.DefaultGlobalTransaction  : [192.168.158.133:8091:2021468859] commit status:Committed
2019-09-06 15:44:35.296  INFO 53904 --- [atch_RMROLE_6_8] i.s.core.rpc.netty.RmMessageListener     : onMessage:xid=192.168.158.133:8091:2021468859,branchId=2021468861,branchType=AT,resourceId=jdbc:mysql://116.62.62.26/seat-order,applicationData=null
2019-09-06 15:44:35.297  INFO 53904 --- [atch_RMROLE_6_8] io.seata.rm.AbstractRMHandler            : Branch committing: 192.168.158.133:8091:2021468859 2021468861 jdbc:mysql://116.62.62.26/seat-order null
2019-09-06 15:44:35.297  INFO 53904 --- [atch_RMROLE_6_8] io.seata.rm.AbstractRMHandler            : Branch commit result: PhaseTwo_Committed

2.storage

2019-09-06 15:44:33.776  INFO 9704 --- [nio-8082-exec-1] c.j.storage.service.StorageServiceImpl   : ------->扣減庫存開始
2019-09-06 15:44:34.030  INFO 9704 --- [nio-8082-exec-1] c.j.storage.service.StorageServiceImpl   : ------->扣減庫存結束
2019-09-06 15:44:35.422  INFO 9704 --- [atch_RMROLE_5_8] i.s.core.rpc.netty.RmMessageListener     : onMessage:xid=192.168.158.133:8091:2021468859,branchId=2021468864,branchType=AT,resourceId=jdbc:mysql://116.62.62.26/seat-storage,applicationData=null
2019-09-06 15:44:35.423  INFO 9704 --- [atch_RMROLE_5_8] io.seata.rm.AbstractRMHandler            : Branch committing: 192.168.158.133:8091:2021468859 2021468864 jdbc:mysql://116.62.62.26/seat-storage null
2019-09-06 15:44:35.423  INFO 9704 --- [atch_RMROLE_5_8] io.seata.rm.AbstractRMHandler            : Branch commit result: PhaseTwo_Committed

3.account

2019-09-06 15:44:34.039  INFO 36556 --- [nio-8081-exec-5] c.j.account.service.AccountServiceImpl   : ------->扣減賬戶開始
2019-09-06 15:44:34.039  INFO 36556 --- [nio-8081-exec-5] c.j.account.service.AccountServiceImpl   : ------->扣減賬戶結束
2019-09-06 15:44:35.545  INFO 36556 --- [atch_RMROLE_3_8] i.s.core.rpc.netty.RmMessageListener     : onMessage:xid=192.168.158.133:8091:2021468859,branchId=2021468867,branchType=AT,resourceId=jdbc:mysql://116.62.62.26/seat-account,applicationData=null
2019-09-06 15:44:35.545  INFO 36556 --- [atch_RMROLE_3_8] io.seata.rm.AbstractRMHandler            : Branch committing: 192.168.158.133:8091:2021468859 2021468867 jdbc:mysql://116.62.62.26/seat-account null
2019-09-06 15:44:35.545  INFO 36556 --- [atch_RMROLE_3_8] io.seata.rm.AbstractRMHandler            : Branch commit result: PhaseTwo_Committed

8.模擬異常

在AccountServiceImpl中模擬異常情況,然後可以查看日誌

    /**
     * 扣減賬戶餘額
     * @param userId 用戶id
     * @param money 金額
     */
    @Override
    public void decrease(Long userId, BigDecimal money) {
        LOGGER.info("------->扣減賬戶開始");
        LOGGER.info("------->Account 模擬異常");
        int i = 1 / 0;
        LOGGER.info("------->扣減賬戶結束");
        accountDao.decrease(userId,money);
    }

9.調用成環

前面的調用鏈爲order->storage->account;
這裏測試的成環是指order->storage->account->order,
這裏的account服務又會回頭去修改order在前面添加的數據。
經過測試,是支持此種場景的。

    /**
     * 扣減賬戶餘額
     * @param userId 用戶id
     * @param money 金額
     */
    @Override
    public void decrease(Long userId, BigDecimal money) {
        LOGGER.info("------->扣減賬戶開始account中");
        //模擬超時異常,全局事務回滾
//        try {
//            Thread.sleep(30*1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        accountDao.decrease(userId,money);
        LOGGER.info("------->扣減賬戶結束account中");

        //修改訂單狀態,此調用會導致調用成環
        LOGGER.info("修改訂單狀態開始");
        String mes = orderApi.update(userId, money.multiply(new BigDecimal("0.09")),0);
        LOGGER.info("修改訂單狀態結束:{}",mes);
    }

在最初的order會創建一個訂單,然後扣減庫存,然後扣減賬戶,賬戶扣減完,會回頭修改訂單的金額和狀態,這樣調用就成環了。

10.seata-server服務端 HA

部署集羣,第一臺和第二臺配置相同,在server端的registry.conf中,注意:

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "eureka"
...... 
  eureka {
    serviceUrl = "http://192.168.xx.xx:8761/eureka"  //兩臺tcc相同,註冊中心的地址
    application = "default" //兩臺tc相同
    weight = "1"  //權重,截至0.9版本,暫時不支持此參數
  }
 ......

注意上述配置和client的配置要一致,2臺和多臺情況相同。

0.9及之前版本,多tc時,tc會誤報異常,此問題0.9之後已經修復,之後的版本應該不會出現此問題。

11.項目整合注意事項(本人整合過程中出現的問題特此記錄以防止再踩坑)

  1. springCloud微服務項目最外層pom.xml,不要有任何共有Jar,比如:

    <?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>
    <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.8.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.*****</groupId>
    <artifactId>*****</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>*****</name>
    <description>parent-project</description>
    <packaging>pom</packaging>
    <!--工程模塊-->
    <modules>
    <module>*****-common</module>
    <module>*****-eureka-server</module>
    <module>*****-zuul-server</module>
    <module>*****-....</module>
    </modules>
    <!--自定義properties屬性-->
    <properties>
    <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
    </properties>
    <!-- SpringCloud Greenwich.SR2 -->
    <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>${spring-cloud.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
    </dependencyManagement>
    <!--定義多環境https://blog.csdn.net/qq_33689414/article/details/81812783-->
    <profiles>
    <profile>
      <id>prod</id>
      <properties>
        <package.environment>prod</package.environment>
      </properties>
    </profile>
    <profile>
      <id>test</id>
      <properties>
        <package.environment>test</package.environment>
      </properties>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
    </profile>
    </profiles>
    <!--插件僅配置公共maven插件,spring-boot-maven-plugin這個插件分別配置到各個微服務避免common打包出現檢測到多個main方法問題及微服務工程依賴不到common.jar問題-->
    <build>
    <!--指定打包包名-->
    <finalName>${project.artifactId}</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>8</source>
          <target>8</target>
          <encoding>utf-8</encoding>
        </configuration>
      </plugin>
    </plugins>
    <resources>
      <resource>
        <directory>src/main/resources/</directory>
        <!--開啓maven filter功能,打包前將功能中的@xx@變量進行替換,如spring.profiles.active根據當前打包指定的環境進行替換-->
        <filtering>true</filtering>
        <includes>
          <!--指定需要將resources文件進行打包-->
          <include>application.yml</include>
          <include>bootstrap.yml</include>
          <include>mapper/*.xml</include>
          <include>static/**</include>
          <include>application-${package.environment}.yml</include>
          <include>logback.${package.environment}.xml</include>
        </includes>
      </resource>
    </resources>
    </build>
    <!--依賴倉庫-->
    <repositories><!-- 代碼庫,改用aliyun的 -->
    <repository>
      <id>maven-ali</id>
      <url>http://maven.aliyun.com/nexus/content/groups/public//</url>
      <releases>
        <enabled>true</enabled>
      </releases>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </repository>
    </repositories>
    <!--插件倉庫,改用aliyun的-->
    <pluginRepositories>
    <pluginRepository>
      <id>alimaven</id>
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
      <releases>
        <enabled>true</enabled>
      </releases>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </pluginRepository>
    </pluginRepositories>
    </project>
    
  2. eureka服務只需要有個spring-cloud-starter-netflix-eureka-server包就可以,其他都不需要,比如:

    <?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>
    <parent>
    <groupId>com.*******</groupId>
    <artifactId>*******</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>*******-eureka-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>vehicle-eureka-server</name>
    <description>註冊中心</description>
    <dependencies>
    <!-- SpringCloud Eureka -->
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
    </dependencies>
    <!--定義多環境https://blog.csdn.net/qq_33689414/article/details/81812783-->
    <profiles>
    <profile>
      <id>prod</id>
      <properties>
        <package.environment>prod</package.environment>
      </properties>
    </profile>
    <profile>
      <id>test</id>
      <properties>
        <package.environment>test</package.environment>
      </properties>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
    </profile>
    </profiles>
    <!--插件僅配置公共maven插件,spring-boot-maven-plugin這個插件分別配置到各個微服務避免common打包出現檢測到多個main方法問題及微服務工程依賴不到common.jar問題-->
    <build>
    <!--指定打包包名-->
    <finalName>${project.artifactId}</finalName>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <inherited>true</inherited>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
    </plugins>
    </build>
    <!--依賴倉庫-->
    <repositories><!-- 代碼庫,改用aliyun的 -->
    <repository>
      <id>maven-ali</id>
      <url>http://maven.aliyun.com/nexus/content/groups/public//</url>
      <releases>
        <enabled>true</enabled>
      </releases>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </repository>
    </repositories>
    <!--插件倉庫,改用aliyun的-->
    <pluginRepositories>
    <pluginRepository>
      <id>alimaven</id>
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
      <releases>
        <enabled>true</enabled>
      </releases>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </pluginRepository>
    </pluginRepositories>
    </project>
    

    以及不要配置什麼file.conf數據源之類的東西;(除了這個服務其他涉及到業務回滾的服務都需要配置)

  3. file.conf、registry.conf與application.yml整合,首先更改seata pom爲:

    <!-- Spring Cloud Seata -->
    <dependency>
      <groupId>com.alibaba.cloud</groupId>
      <artifactId>spring-cloud-alibaba-seata</artifactId>
      <version>2.2.0.RELEASE</version>
      <exclusions>
        <exclusion>
          <groupId>io.seata</groupId>
          <artifactId>seata-spring-boot-starter</artifactId>
        </exclusion>
        <exclusion>
          <artifactId>seata-all</artifactId>
          <groupId>io.seata</groupId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>io.seata</groupId>
      <artifactId>seata-spring-boot-starter</artifactId>
      <version>1.1.0</version>
    </dependency>
    <dependency>
      <groupId>io.seata</groupId>
      <artifactId>seata-all</artifactId>
      <version>1.1.0</version>
    </dependency>
    
  4. 啓動類不需要加excu**排除自動代理,因爲我用的是hikari所以新增如下類:

    @Configuration
    public class DataSourceConfigure {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.hikari")
    public DataSource dataSource() {
    return new HikariDataSource();
    }
    }
    

    新增application.yml內容爲:

    seata:
    enabled: true
    application-id: user
    tx-service-group: ksc_tx_group #自定義名字保持統一
    enable-auto-data-source-proxy: false
    service:
    vgroupMapping:
      ksc_tx_group: seata-server #默認default,這個是seate的名字,改了之後需要改服務端registry.conf 中eureka  application = "seata-server",保持統一
    enable-degrade: false
    disable-global-transaction: false
    registry:
    type: eureka
    eureka:
      service-url: http://localhost:8888/eureka/
    weight: 1
    config:
    type: file
    

    出現問題多看看github例子即可解決,新東西版本差別很大注意區別

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章