【shardingsphere 5.x版本使用】,精准分表自定义策略配置,单库分表

之前有发过4.x版本的使用教程,这次项目升级了5.x版本,教程实战贴一下

1. 首先是maven依赖的添加

        <!-- Sharding-JDBC -->
        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
            <version>5.1.2</version>
        </dependency>

2. yaml的配置,只配置一个数据库,单库分表,使用精准自定义分片策略

5.1.2版本增加一个参数props,将分片策略和全限定类名配置在这个下面。
而且精准分片的接口StandardShardingAlgorithm实现类需要实现的方法也多了两个,getProps和


    @Override
    public String doSharding(Collection<T> tableNames, PreciseShardingValue<T> preciseShardingValue) {
        return null;
    }

    @Override
    public Collection<String> doSharding(Collection<T> collection, RangeShardingValue<T> rangeShardingValue) {
        return null;
    }

    @Override
    public String getType() {
        return null;
    }

	// 新增方法,暂不知用处
    @Override
    public Properties getProps() {
        return null;
    }
    
    // 新增方法 删除了原init();方法,多了个参数properties
    @Override
    public void init(Properties properties) {

    }
spring:
  main:
    allow-bean-definition-overriding: true
  shardingsphere:
    # 是否启用 Sharding
    enabled: true
    # 打印sql
    props:
      sql-show: true
    datasource:
      names: master
      master:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/**?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8
        username: root
        password: root
    rules:
      sharding:
        # 表策略配置
        tables:
          # terminal_heartbeat 是逻辑表
          terminal_heartbeat:
            actualDataNodes: master.**
            tableStrategy:
              # 使用标准分片策略
              standard:
                # 配置分片字段
                shardingColumn: terminal_code
                # 分片算法名称,不支持大写字母和下划线,否则启动就会报错
                shardingAlgorithmName: time-sharding-altorithm
        # 分片算法配置
        shardingAlgorithms:
          # 分片算法名称,不支持大写字母和下划线,否则启动就会报错
          time-sharding-altorithm:
            # 类型:自定义策略
            type: CLASS_BASED
            props:
              # 分片策略
              strategy: standard
              # 分片算法类
              algorithmClassName: com.****.ShardingAlgorithmA

3. 踩坑合集:

  1. ShardingJDBC 5.1.0使用druid连接池需要加dbcp依赖
<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-dbcp</artifactId>
    <version>10.0.16</version>
</dependency>
  1. 与flyway一起使用时会报错,因为flyway会查询 information_schema.schemata 用户权限和数据库表集合等信息,而ShardingJDBC暂未支持
    官方回复5.1.1已支持pr地址:https://github.com/apache/shardingsphere/issues/16234

但是我已尝试还是无效,会报错org.apache.shardingsphere.infra.exception.SchemaNotExistedException: Schema ‘information_schema’ 不存在

解决方法:使用Sharding-proxy,或者禁用flyway

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个基本的 Shardingsphere 分库分表 demo 配置: 1. 引入依赖 首先需要在项目中引入 Shardingsphere 的相关依赖,具体版本号可根据需求自行选择。 ```xml <!-- ShardingSphere JDBC Core APIs --> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>sharding-core-jdbc</artifactId> <version>${sharding.version}</version> </dependency> <!-- ShardingSphere JDBC Spring Boot Starter --> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>sharding-jdbc-spring-boot-starter</artifactId> <version>${sharding.version}</version> </dependency> ``` 2. 配置数据源 在 application.yml 中配置数据源信息,包括主库和从库的信息。 ```yml spring: datasource: # 主库数据源 master: jdbc-url: jdbc:mysql://localhost:3306/master_db?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver # 从库数据源 slave1: jdbc-url: jdbc:mysql://localhost:3306/slave_db1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver slave2: jdbc-url: jdbc:mysql://localhost:3306/slave_db2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver ``` 3. 配置分库分表规则 在 application.yml 中配置分库分表规则,包括分库规则和分表规则。 ```yml sharding: # 分库规则 default-database-strategy: standard: sharding-column: user_id precise-algorithm-class-name: com.example.demo.algorithm.ModuloDatabaseShardingAlgorithm # 分表规则 tables: user: actual-data-nodes: master.user_${0..1} table-strategy: standard: sharding-column: id precise-algorithm-class-name: com.example.demo.algorithm.ModuloTableShardingAlgorithm ``` 其中,ModuloDatabaseShardingAlgorithm 和 ModuloTableShardingAlgorithm 是自定义的分库分表算法,这里只是简单示例。 4. 编写 DAO 层代码 在 DAO 层编写相应的代码,使用 ShardingSphere 提供的 API 完成数据库操作,例如: ```java @Repository public class UserDaoImpl implements UserDao { private final JdbcTemplate jdbcTemplate; @Autowired public UserDaoImpl(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public User getById(Long id) { String sql = "SELECT * FROM user WHERE id = ?"; return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(User.class)); } @Override public void save(User user) { String sql = "INSERT INTO user(id, user_id, name) VALUES (?, ?, ?)"; jdbcTemplate.update(sql, user.getId(), user.getUserId(), user.getName()); } } ``` 5. 测试分库分表效果 编写测试代码,测试分库分表的效果,例如: ```java @SpringBootTest class UserDaoImplTest { @Autowired private UserDao userDao; @Test void testSave() { User user = new User(); user.setId(1L); user.setUserId(1L); user.setName("张三"); userDao.save(user); } @Test void testGetById() { User user = userDao.getById(1L); System.out.println(user); } } ``` 至此,一个简单的 Shardingsphere 分库分表 demo 配置就完成了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值