分库分表

3. SpringBoot整合ShardingJdbc单库分表

2020-05-12  本文已影响0人  茶还是咖啡

基础信息请参照 https://www.jianshu.com/p/865c18d006a5

一个数据库实例上将表进行水平拆分,将数据根据一定的规则路由到两张表中。
eg



该示例中,将用户表分成了两个字表,分表是t_user1和t_user0,他们的表结构完全相同。

ER图如下

我们按照用户的性别,对表数据进行路由,性别为0的在t_user0表,性别为1 的在t_user1表,具体的配置如下:

dataSources:
  ds0: !!com.zaxxer.hikari.HikariDataSource
    driverClassName: com.mysql.cj.jdbc.Driver
    jdbcUrl: jdbc:mysql://localhost:3306/order1?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
    username: root
    password: root
shardingRule:
  tables:
    t_user:
      actualDataNodes: ds0.t_user$->{0..1}
      tableStrategy:
        inline:
          shardingColumn: sex
          algorithmExpression: t_user$->{sex % 2}
  bindingTables:
    - t_user
  defaultKeyGenerator:
    type: SNOWFLAKE
    column: id
props:
  sql.show: true

详细的配置信息可以参照官网
https://shardingsphere.apache.org/document/current/cn/manual/sharding-jdbc/configuration/config-yaml/

数据源配置

@Component
public class DataSourceConfig {

    @Resource
    private ShardingDataSourceYamlConfig shardingDataSourceYamlConfig;

    @Bean
    @Primary
    public DataSource dataSource() throws IOException, SQLException {
        return YamlShardingDataSourceFactory.createDataSource(shardingDataSourceYamlConfig.getShardingFileByProfileActive());
    }
}

项目地址:https://github.com/xiao-ren-wu/sharding-all/tree/master/sub-table

上一篇 下一篇

猜你喜欢

热点阅读