首先,确保Seata-Server & Nacos 已经启动完毕

1. 导入相关依赖

导入seata的springcloud 启动器以及seata的依赖包(不要使用启动器中自带的seata-all,选择与你Seata-Server相同版本的依赖[如这是1.3.0])

  1. <dependency>
  2. <groupId>com.alibaba.cloud</groupId>
  3. <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
  4. <exclusions>
  5. <exclusion>
  6. <groupId>io.seata</groupId>
  7. <artifactId>seata-all</artifactId>
  8. </exclusion>
  9. </exclusions>
  10. </dependency>
  11. <dependency>
  12. <groupId>io.seata</groupId>
  13. <artifactId>seata-all</artifactId>
  14. <version>1.3.0</version>
  15. </dependency>

2. 复制file.conf和registry.conf到resources文件夹

3. 创建代理数据源

  1. package cn.net.easycamp.carnetwork.order.config;
  2. import com.alibaba.druid.pool.DruidDataSource;
  3. import io.seata.rm.datasource.DataSourceProxy;
  4. import org.apache.ibatis.session.SqlSessionFactory;
  5. import org.mybatis.spring.SqlSessionFactoryBean;
  6. import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
  7. import org.springframework.beans.factory.annotation.Value;
  8. import org.springframework.boot.context.properties.ConfigurationProperties;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.context.annotation.Configuration;
  11. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  12. import javax.sql.DataSource;
  13. @Configuration
  14. public class DataSourceProxyConfig {
  15. @Value("${mybatis.mapper-locations}")
  16. private String mapperLocations;
  17. @Bean
  18. @ConfigurationProperties(prefix = "spring.datasource")
  19. public DataSource druidDataSource(){
  20. return new DruidDataSource();
  21. }
  22. @Bean
  23. public DataSourceProxy dataSourceProxy(DataSource dataSource){
  24. return new DataSourceProxy(dataSource);
  25. }
  26. @Bean
  27. public SqlSessionFactory sqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws Exception{
  28. SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
  29. sqlSessionFactoryBean.setDataSource(dataSourceProxy);
  30. sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
  31. sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
  32. return sqlSessionFactoryBean.getObject();
  33. }
  34. }

4. 修改主启动类的注解,排除默认的数据源自动装配

  1. @SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

5. 修改application.yml

添加如下的配置

  1. spring:
  2. cloud:
  3. alibaba:
  4. seata:
  5. tx-service-group: fsp_tx_group # 这个名称需要和Seata-server中配置的名称相同

6. 配置完成,可以编写业务测试