Sharding-jdbc + Seata + Nacos整合

2022年7月8日 1213点热度 1人点赞 4条评论

前置条件

先了解Sharding-jdbc、Seata、Nacos这三样东西各自的作用以及单独使用时的配置。

整合代码已放在github,详细步骤章节请搭配此项目看,欢迎start

思路

如果已经做过Seata + Nacos的整合的,直接看最后的Seata结合Sharding-jdbc章节

详细步骤

Nacos + Seata服务端整合

我之前写过,不再赘述,引流:****Seata-初体验以及避坑****

项目工程整合Seata

参考文档:seata-example

  1. nacos服务端新增配置seata.properties

    Untitled

  2. application.yml增加seata配置

    # 服务发现
    spring:
      cloud:
        nacos:
          discovery:
            server-addr: localhost:8848
            username: nacos
            password: nacos
      application:
        name: order-service
    # seata配置
    seata:
      enabled: true
      application-id: {spring.application.name}
      tx-service-group:{spring.application.name}-tx-group
      # 配置中心
      config:
        type: nacos
        nacos:
          serverAddr: localhost:8848
          dataId: "seata.properties"
          username: nacos
          password: nacos
      # 注册中心
      registry:
        type: nacos
        nacos:
          application: seata-server
          server-addr: localhost:8848
          username: nacos
          password: nacos
      # seata默认使用cglib代理,整合sharding-jdbc会爆错,提示ShardingSphereDataSource无法序列化,有知道怎么解决的朋友,诚心希望告知下
      use-jdk-proxy: true
    

项目工程整合Sharding-jdbc

就是普通的springboot整合Sharding-jdbc,细说的话内容太多,不赘述。

可参考官方文档和我的案例工程

Seata结合Sharding-jdbc

参考文档

  1. 添加Sharding-jdbc 柔性事务jar包
    <dependency>
        <groupId>org.apache.shardingsphere</groupId>
        <artifactId>shardingsphere-transaction-base-seata-at</artifactId>
        <version>${shardingsphere.version}</version>
    </dependency>
    
  2. 每个分片数据库添加undo_log表

  3. classpath(springboot中就是resource目录)中增加seata.conf文件
  4. 将Seata的事务(上面)注解换成Sharding-jdbc(下面两行)的

    // seata事务注解
    @GlobalTransactional
    
    @Transactional // spring的事务注解
    @ShardingSphereTransactionType(TransactionType.BASE) // Sharding-jdbc柔性事务
    

求助

有没有大佬知道怎么处理Seata整合Sharding-jdbc时,cglib序列化ShardingSphereDataSource报错的问题?欢迎讨论

参考资料

ShardingSphere-Seata事务

alibaba-stata-example

王谷雨

一个苟且偷生的java程序员

文章评论

  • 可乐加冰

    cglib序列化ShardingSphereDataSource报错的问题?

    请问这个问题解决了码

    2022年8月10日
    • 王谷雨

      @可乐加冰 没有,因为项目用不上Sharding-jdbc,没有投入更多精力在这里。不好意思哈。

      2022年8月11日
    • 王谷雨

      @可乐加冰 在github上也有人讨论这个问题,有个人给出的方案是既然报错是因为ShardingSphereDataSource动态代理导致的,那就让ShardingSphereDataSource不被spring动态代理就好。可以去看https://github.com/apache/shardingsphere/issues/15086里面nealzyf这个人的回复。但是我按照这个人提供的方案去试了下,没有成功,因为我没法解决AutoProxyUtils#isOriginalInstance的判断问题。
      而我这边目前的方法是:
      方法1:使用jdk代理
      方法2:将ShardingSphereDataSource改成非final类
      因为我工作中暂时用不到ShardingJdbc,所以以上两种方法都只能保证启动不报错,未在使用中验证,请谨慎选择。

      2022年10月29日
  • jaay1219

    @EnableTransactionManagement
    // 使用jdk动态代理可以解决ShardingSphereDataSource报错问题
    @EnableAutoDataSourceProxy(useJdkProxy = true)
    public class UserCenterApplication
    ------------------------------------------------------------
    seata:
    use-jdk-proxy: true
    这个配置不生效,加了没用

    2023年5月7日