水平分表
引入依赖
<!--分库分表使用-->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.0.0-RC1</version>
</dependency>
建表并生成实体类
1,新建表course_0,course_1 2,利用插件生成mp代码并将表名改成course
配置文件
#分库分表数据源配置----水平分表配置
#一个实体类对应两张表,覆盖
spring.main.allow-bean-definition-overriding=true
#配置数据源,给数据源起名
spring.shardingsphere.datasource.names=ds
spring.shardingsphere.datasource.ds.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.ds.url=jdbc:mysql://localhost:3306/asset_new?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8
spring.shardingsphere.datasource.ds.username=root
spring.shardingsphere.datasource.ds.password=123456
spring.shardingsphere.datasource.ds.type=org.apache.commons.dbcp2.BasicDataSource
#指定course表分布情况,配置表在哪个数据库里面,表名称都是什么 ds.course_0 ds.course_1
spring.shardingsphere.sharding.tables.course.actual-data-nodes=ds.course_$->{0..1}
#指定表分片策略
#cid为偶数数据添加到ds(course_db)的course_0表,cid为奇数数据添加到ds(course_db)的course_1表
spring.shardingsphere.sharding.tables.course.table-strategy.inline.sharding-column=cid
spring.shardingsphere.sharding.tables.course.table-strategy.inline.algorithm-expression=course_$->{cid % 2}
#指定course表里面主键cid生成策略
spring.shardingsphere.sharding.tables.course.key-generator.column=cid
spring.shardingsphere.sharding.tables.course.key-generator.type=SNOWFLAKE
#打开sql输出日志
spring.shardingsphere.props.sql.show=true
垂直分表
可直接手动拆分表实现。
读写分离
spring.shardingsphere.datasource.master.type=org.apache.commons.dbcp2.BasicDataSource
spring.shardingsphere.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.master.url=jdbc:mysql://192.168.30.129:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
spring.shardingsphere.datasource.master.username=root
spring.shardingsphere.datasource.master.password=123456
spring.shardingsphere.datasource.slave.type=org.apache.commons.dbcp2.BasicDataSource
spring.shardingsphere.datasource.slave.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.slave.url=jdbc:mysql://192.168.30.129:3307/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
spring.shardingsphere.datasource.slave.username=root
spring.shardingsphere.datasource.slave.password=123456
# 一个实体类对应两张表,覆盖
spring.main.allow-bean-definition-overriding=true
#配置数据源,给数据源起名
spring.shardingsphere.datasource.names=master,slave
#配置默认数据源,主要用于写
spring.shardingsphere.sharding.default-data-source-name=master
#配置主从名称
spring.shardingsphere.masterslave.name=ms
spring.shardingsphere.masterslave.master-data-source-name=master
spring.shardingsphere.masterslave.slave-data-source-names=slave
# 打开sql输出日志
spring.shardingsphere.props.sql.show=true
|