mybatis垂直分库_Sharding-Sphere-JDBC垂直分表,分库例子

本文介绍了如何使用Sharding-Sphere-JDBC进行垂直分库分表,以用户信息和帖子信息为例,分别存入test和test1数据库中。通过配置两个数据源ds0和ds1,结合mybatis实现业务逻辑,详细展示了相关数据库配置和分片策略。
摘要由CSDN通过智能技术生成

朋也的博客 » 首页 » 文章

Sharding-Sphere-JDBC垂直分表,分库例子

作者:朋也

日期:2020-06-03

版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)

目的:根据业务(用户信息,帖子信息)将数据存如不同数据库中,我这以用户信息存入test库中,帖子信息存入test1库中为例

垂直分表没必要用sharding-sphere,根据分库分表的原理来看,垂直分表就是将一个表细分,且在同一个库里,正常操作即可,下面介绍一下分库的垂直拆分

一个论坛业务,拆分成用户信息一个库,帖子相关的一个库的话,一般做法是配置两个数据源【可参见这篇博客:springboot集成mybatis配置主从复制双库实现读写分离】,通过给mybatis的mapper配置不同的数据源来实现业务,使用sharding-sphere逻辑也是大同小异,看配置

# 指定数据源名,如果有两个,用逗号隔开 如:ds0,ds1,相应的下面也要配置上ds1的连接地址

spring.shardingsphere.datasource.names=ds0,ds1

# 配置数据源

spring.shardingsphere.datasource.ds0.type=com.zaxxer.hikari.HikariDataSource

spring.shardingsphere.datasource.ds0.driver-class-name=com.mysql.cj.jdbc.Driver

spring.shardingsphere.datasource.ds0.jdbc-url=jdbc:mysql://localhost:3306/test?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai

spring.shardingsphere.datasource.ds0.username=root

spring.shardingsphere.datasource.ds0.password=123123

# ds1

spring.shardingsphere.datasource.ds1.type=com.zaxxer.hikari.HikariDataSource

spring.shardingsphere.datasource.ds1.driver-class-name=com.mysql.cj.jdbc.Driver

spring.shardingsphere.datasource.ds1.jdbc-url=jdbc:mysql://localhost:3306/test1?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai

spring.shardingsphere.datasource.ds1.username=root

spring.shardingsphere.datasource.ds1.password=123123

# 指定user表名规则

spring.shardingsphere.sharding.tables.user.actual-data-nodes=ds0.user_$->{0..1}

spring.shardingsphere.sharding.tables.user.table-strategy.inline.sharding-column=id

spring.shardingsphere.sharding.tables.user.table-strategy.inline.algorithm-expression=user_$->{id % 2}

# 指定user表主键名以及主键生成策略SNOWFLAKE(雪花算法)

spring.shardingsphere.sharding.tables.user.key-generator.column=id

spring.shardingsphere.sharding.tables.user.key-generator.type=SNOWFLAKE

# 指定topic表名规则

spring.shardingsphere.sharding.tables.topic.actual-data-nodes=ds1.topic_$->{0..1}

spring.shardingsphere.sharding.tables.topic.table-strategy.inline.sharding-column=id

spring.shardingsphere.sharding.tables.topic.table-strategy.inline.algorithm-expression=topic_$->{id % 2}

# 指定topic表主键名以及主键生成策略SNOWFLAKE(雪花算法)

spring.shardingsphere.sharding.tables.topic.key-generator.column=id

spring.shardingsphere.sharding.tables.topic.key-generator.type=SNOWFLAKE

# 打印sql

spring.shardingsphere.props.sql.show=true

说明:

两个数据源,ds0,ds1,给表user指定策略为存入ds0里,然后再根据id在奇偶判断存入哪个user表中,相应的给topic表指定数据源ds1,且分表逻辑跟user一样

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值