sharding-jdbc与springboot结合使用-单库分表简单使用

sharding-jdbc官网:

https://shardingsphere.apache.org/document/current/cn/quick-start/sharding-jdbc-quick-start/

sharding-jdbc springboot配置:

https://shardingsphere.apache.org/document/current/cn/manual/sharding-jdbc/configuration/config-spring-boot/

1、添加依赖

sharding-jdbc与springboot结合使用-单库分表简单使用
 <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
</dependency>
<dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
            <version>4.0.0-RC1</version>
</dependency>
View Code

2、配置文件方式

sharding-jdbc与springboot结合使用-单库分表简单使用
spring.shardingsphere.props.sql.show=true
spring.shardingsphere.datasource.names=master
spring.shardingsphere.datasource.master.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.master.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.shardingsphere.datasource.master.url=jdbc:oracle:thin:@XXXX:1521:XXX
spring.shardingsphere.datasource.master.username=XXX
spring.shardingsphere.datasource.master.password=XXX

spring.shardingsphere.sharding.tables.student.actual-data-nodes=master.student_${0..1}
spring.shardingsphere.sharding.tables.student.table-strategy.inline.sharding-column=age
spring.shardingsphere.sharding.tables.student.table-strategy.inline.algorithm-expression=student_${age % 2}

#spring.shardingsphere.sharding.tables.STUDENT.table-strategy.standard.sharding-column=AGE
#spring.shardingsphere.sharding.tables.STUDENT.table-strategy.standard.precise-algorithm-class-name=com.chamc.rics.basics.test.algorithm.MyPreciseShardingAlgorithm


#spring.sharding.jdbc.config.sharding.default-table-strategy.standard.sharding-column=USER_ID
##精确分片算法,用于=和IN,实现类
#sharding.jdbc.config.sharding.default-table-strategy.standard.precise-algorithm-class-name=com.solider76.oo.service.chat.config.MyShardingConfig
##范围分片算法,用于BETWEEN,实现类
#sharding.jdbc.config.sharding.default-table-strategy.standard.range-algorithm-class-name=com.solider76.oo.service.chat.config.MyShardingConfig
View Code

3、自定义方式

  参照官网及大牛的文章:http://wuwenliang.net/categories/Sharding-JDBC/

4、异常解决

sharding-jdbc与springboot结合使用-单库分表简单使用

对于保存数据操作,报错。原因是配置文件中:

spring.shardingsphere.sharding.tables.student.table-strategy.inline.algorithm-expression=student_${age % 2}

student写成了大写,出现 不能对null 取mod()操作。

 

上一篇:Sharding-JDBC实现水平拆分-单库分表


下一篇:分库分表(3) ---SpringBoot + ShardingSphere 实现读写分离