seata分布式事务--看这一篇就够了~

  本人小白哈,如果写的有错误或者不对的 欢迎留言评论。

首次接触分布式事务,在选型的时候并没有选中lcn,而且选择了阿里开源的 seata框架,看了很多文章说是,无侵入性,咱也不知道,咱也没敢问。

seata的wiki文档【seataWIKI文档】

seata的官方demo【seata官方DEMO】

 我是想着第一次接触,就不用官网的DEMO示例了,先自己搭建一个吧~(入坑了)

项目是用springcloud+mybatisplus+seata+druid+feign集成的,

spring cloud-->2.1.6.RELEASE    版本:Greenwich.SR2

mybatis plus -->3.1.0

seata -->0.7.1

druid-->1.1.2

feign组件是openfeign

项目长成这个艹性,别喷我,我是自己瞎玩的,你要是喷我 我估计也要怼你哦,哈哈

seata分布式事务--看这一篇就够了~_第1张图片

其实项目还有很多不完善的地方,还没时间去优化,下一步会加上分布式锁,想用readLock,哈哈

第一个模块示例图:目的是想着只新增maven依赖,还有一些公共配置,现在好像做反了。

seata分布式事务--看这一篇就够了~_第2张图片

pom.xml文件

seata分布式事务--看这一篇就够了~_第3张图片


    
        org.springframework.boot
        spring-boot-starter
    
    
        org.springframework.cloud
        spring-cloud-starter-netflix-eureka-client
    
    
        io.seata
        seata-all
        ${seata.version}
    
    
        io.seata
        seata-core
        ${seata.version}
    
    
        com.alibaba.fescar
        fescar-rm-datasource
        ${fescar-rm.version}
    
    
        com.alibaba.fescar
        fescar-spring
        ${fescar-rm.version}
    


    
        org.springframework
        spring-web
    
    
        org.springframework.boot
        spring-boot-starter-web
    
    
        org.springframework.boot
        spring-boot-configuration-processor
        true
    
    
    
        com.alibaba
        druid-spring-boot-starter
        ${druid.version}
    
    
        mysql
        mysql-connector-java
        runtime
    
    
    
        org.projectlombok
        lombok
        ${lombok.version}
    
    
    
        com.alibaba
        fastjson
        ${fastjson.version}
    
    
    
        com.baomidou
        mybatis-plus-boot-starter
        ${mybatis-puls.version}
    
    
        com.baomidou
        mybatis-plus
        ${mybatis-puls.version}
    
          
        org.freemarker
        freemarker
    

第二个模块示例图:这个作为被调用方,专业术语叫什么RM还是TM来着,后面再更新吧

seata分布式事务--看这一篇就够了~_第4张图片

基础业务层 不想多做介绍哈。正常使用自动生成文件,生成就OK了,放入自己的项目里面。

介绍一下下面的几个:application.properties,file.conf,registry.confdruid包下的

1、application.properties

server.port= 6666
spring.application.name=seata-animal
eureka.instance.hostname=localhost
eureka.client.service-url.defaultZone= http://${eureka.instance.hostname}:8888/eureka/
spring.cloud.alibaba.seata.tx-service-group=my_transation  
logging.level.org.springframework.cloud.alibaba.seata.web=debug
logging.level.io.seata=debug


# 驱动配置信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/xx?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver

#连接池的配置信息
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall,slf4j
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
mybatis-plus.mapper-locations=classpath:mapper/*.xml
mybatis-plus.type-aliases-package=com.gzf.pojo
spring.cloud.alibaba.seata.tx-service-group=my_transation这里设置的 要和 file.conf里面的vgroup_mapping.XX对应起来  我这里是my_transation  那file.conf里面应该是   vgroup_mapping.my_transation   否则就会报错。如下:

         com.alibaba.fescar.common.exception.FrameworkException: can not connect to fescar-server.

2、file.conf

transport {
  # tcp udt unix-domain-socket
  type = "TCP"
  #NIO NATIVE
  server = "NIO"
  #enable heartbeat
  heartbeat = true
  #thread factory for netty
  thread-factory {
    boss-thread-prefix = "NettyBoss"
    worker-thread-prefix = "NettyServerNIOWorker"
    server-executor-thread-prefix = "NettyServerBizHandler"
    share-boss-worker = false
    client-selector-thread-prefix = "NettyClientSelector"
    client-selector-thread-size = 1
    client-worker-thread-prefix = "NettyClientWorkerThread"
    # netty boss thread size,will not be used for UDT
    boss-thread-size = 1
    #auto default pin or 8
    worker-thread-size = 8
  }
}
service {
  #vgroup->rgroup
  vgroup_mapping.my_transation = "default"    
  #only support single node
  localRgroup.grouplist = "127.0.0.1:8091"
  #degrade current not support
  enableDegrade = false
  #disable
  disable = false
}

client {
  async.commit.buffer.limit = 10000
  lock {
    retry.internal = 10
    retry.times = 30
  }
}
需要注意的点:
        1、vgroup_mapping.my_transation = "default"   需要对应配置文件里面的 spring.cloud.alibaba.seata.tx-service-group=my_transation

           2、localRgroup.grouplist = "127.0.0.1:8091" 是对应的      seata-server服务的【seata-server下载】,具体配置下面再讲,我先讲完代码。。

3、registry.conf   纯复制吧,,

registry {
  # file nacos
  type = "file"

  nacos {
    serverAddr = "localhost"
    namespace = "public"
    cluster = "default"
  }
  file {
    name = "file.conf"
  }
}

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

  file {
    name = "file.conf"
  }
}

4、druid包

seata分布式事务--看这一篇就够了~_第5张图片

一个一个来 DataBasaeConfiguration.java

强调的是 引包问题  

这里说明一下,seata是要在数据源处做代理的,具体就看官方介绍吧,上面有链接。

@Bean(initMethod = "init", destroyMethod = "close")     //声明其为Bean实例
    @Primary  //在同样的DataSource中,首先使用被标注的DataSource
    public DruidDataSource dataSource() {
        DruidDataSource datasource = new DruidDataSource();

        datasource.setUrl(this.dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);

        //configuration
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        try {
            datasource.setFilters(filters);
        } catch (SQLException e) {
            log.info("druid configuration initialization filter",e);
        }
        datasource.setConnectionProperties(connectionProperties);

        return datasource;
    }


//代理
 @Bean
    public DataSourceProxy dataSourceProxy(DruidDataSource druidDataSource) {
        //com.alibaba.fescar.rm.datasource.DataSourceProxy;   fescar-rm-datasource
        return new DataSourceProxy(druidDataSource);
    }


     /**这个拦截器的流程是,feign远程调用开始的时候 会在RequestHeaderInterceptor中拦截XID,
     * 然后再SeataXidFilter里面获取XID,保证事务能够传播到远程服务,保证事务成功/回滚
     * @Description:
     * @Author:gaozifeng
     * @Date 2019/7/26 18:05
     **/
    @Bean
    public SeataXidFilter fescarXidFilter() {
        return new SeataXidFilter();
    }

   /**捕捉全局GlobalTransactionScanner
     * 和file中vgroup_mapping.my_transation 后缀保持一致  否则出现连接不上或者 注册RM 失败.
     * 且和配置文件中的spring.cloud.alibaba.seata.tx-service-group 保持一致
     * @param :
     * @return : io.seata.spring.annotation.GlobalTransactionScanner
     * @author : gaozifeng
     * @date : 2019/7/29 20:45
     */
    @Bean
    public GlobalTransactionScanner globalTransactionScanner() {
        return new GlobalTransactionScanner("seata-animal", "my_transation");
    }

    @Bean(name = "mysqlUserTransactionManager")
    public DataSourceTransactionManager initTransactionManager(@Autowired DataSourceProxy dataSource) {
        try {
            return new DataSourceTransactionManager(dataSource);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Bean(name = "mysqlUserSqlSessionFactory")
    public SqlSessionFactory initSqlSessionFactory(@Autowired DataSourceProxy dataSource
            , @Autowired PaginationInterceptor paginationInterceptor)
            throws Exception {

        MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        mybatisSqlSessionFactoryBean.setDataSource(dataSource);

        MybatisConfiguration mybatisConfiguration = new MybatisConfiguration();
        mybatisConfiguration.setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class);
        mybatisConfiguration.setMapUnderscoreToCamelCase(true);
        mybatisSqlSessionFactoryBean.setConfiguration(mybatisConfiguration);

        mybatisSqlSessionFactoryBean.setPlugins(new Interceptor[]{paginationInterceptor});

        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        mybatisSqlSessionFactoryBean.setTypeAliasesPackage("com.gzf.pojo");
        //开启mapper扫描
        mybatisSqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        mybatisSqlSessionFactoryBean.setVfs(SpringBootVFS.class);
        return mybatisSqlSessionFactoryBean.getObject();
    }

    /**
     * mybatis-plus分页插件
* 文档:http://mp.baomidou.com
*/ @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); return paginationInterceptor; }

 RequestHeaderInterceptor.java  准确来说,这个是要用在seata-animal上面的,因为seata-user会使用feign调用animal项目,可能理解有误哈

/**
 * Feign拦截器,把RootContext中的XID(XID用于标识一个局部事务属于哪个全局事务,需要在调用链路的上下文中传递)传递到上层调用链路
 * 
 * @author gzf
 * @time 2019.07.31
 */
@Component
public class RequestHeaderInterceptor implements RequestInterceptor {

	@Override
	public void apply(RequestTemplate template) {
		String xid = RootContext.getXID();
		if (StringUtils.isNotBlank(xid)) {
			template.header(SeataConstant.XID_HEADER, xid);
		}
	}

}
SeataConstant.java 固定
public class SeataConstant {
	/** seata Xid header */
	public static final String XID_HEADER = "Xid_Header";
}
SeataXidFilter.java  不难理解
/**
 * Http Rest请求拦截器,用于把当前上下文中获取到的XID放到RootContext
 * @author gzf
 * @time 2019.07.31
 */
public class SeataXidFilter extends OncePerRequestFilter {
	protected Logger logger = LoggerFactory.getLogger(SeataXidFilter.class);

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String xid = RootContext.getXID();
		String restXid = request.getHeader(SeataConstant.XID_HEADER);
		boolean bind = false;
		if (StringUtils.isBlank(xid) && StringUtils.isNotBlank(restXid)) {
			RootContext.bind(restXid);
			bind = true;
			if (logger.isDebugEnabled()) {
				logger.debug("bind[" + restXid + "] to RootContext");
			}
		}
		try {
			filterChain.doFilter(request, response);
		} finally {
			if (bind) {
				String unbindXid = RootContext.unbind();
				if (logger.isDebugEnabled()) {
					logger.debug("unbind[" + unbindXid + "] from RootContext");
				}
				if (!restXid.equalsIgnoreCase(unbindXid)) {
					logger.warn("xid in change during http rest from " + restXid + " to " + unbindXid);
					if (unbindXid != null) {
						RootContext.bind(unbindXid);
						logger.warn("bind [" + unbindXid + "] back to RootContext");
					}
				}
			}
		}

	}

}
AnimalServiceImpl.java 作为服务调用方, 这里最好是记录一个返回值,否则的话,操作过程中如果出现问题,就会导致服务之间事务失败。

seata分布式事务--看这一篇就够了~_第6张图片

被调用方介绍到这里,下面看一下调用方。

seata-user  如上 除了ServiceImpl不同 其他 除了类名都相同。

seata分布式事务--看这一篇就够了~_第7张图片

这里只新增了一个@GlobalTransactional,识别全局事务id,此ID会由seata来生成,规则是ip+port+transactionid

首先说一下,在本项目执行完userMapper.save方法之后,会在数据库生成对应的undo_log,日志。如果接下来项目出错,就会用日志回滚了。

代码介绍完了,剩下来就介绍一下seata-server端了。

这个端其实不难,

我做了一个文件的更改  registry文件

seata分布式事务--看这一篇就够了~_第8张图片

然后就启动 bin 下面的 文件吧,

 

贴一下成功案例哈,

seata分布式事务--看这一篇就够了~_第9张图片

undo_log  

事务成功:业务库保留数据,undo_log记录 会在异步开启线程执行删除;

事务失败:业务库删除数据,undo_log保留记录;

项目也开源了

https://gitee.com/wqnmlgbaw/seata-gzf  欢迎下载 

转载请标志出处哈,

你可能感兴趣的:(mybatis,seata,feign,springcloud)