本文是Sharding-JDBC采用Spring Boot Starter方式配置第二篇,第一篇是读写分离讲解,请参考:《Spring Boot中整合Sharding-JDBC读写分离示例》

在我《Spring Cloud微服务-全栈技术与案例解析》书中都是通过XML方式配置。今天给大家演示的是单库中分表的操作,如果用XML方式配置,那么就是下面的配置:

  <!-- 数据源 -->
<bean id="ds_0" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close" primary="true">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/ds_0?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="123456" />
</bean> <!-- algorithm-class="com.fangjia.sharding.UserSingleKeyTableShardingAlgorithm" -->
<!-- user_0,user_1,user_2,user_3 -->
<rdb:strategy id="userTableStrategy" sharding-columns="id" algorithm-expression="user_${id.longValue() % 4}"/>
<rdb:data-source id="dataSource">
<rdb:sharding-rule data-sources="ds_0">
<rdb:table-rules>
<rdb:table-rule logic-table="user" actual-tables="user_${0..3}" table-strategy="userTableStrategy"/>
</rdb:table-rules>
<rdb:default-database-strategy sharding-columns="none" algorithm-class="com.dangdang.ddframe.rdb.sharding.api.strategy.database.NoneDatabaseShardingAlgorithm"/>
</rdb:sharding-rule>
</rdb:data-source>

我们将user表分成了4个,分别是user_0,user_1,user_2,user_3,通过id取模的方式决定数据落在哪张表上面。

如果用Spring Boot方式配置自然就简单多了,如下:

sharding.jdbc.datasource.names=ds_master
# 数据源
sharding.jdbc.datasource.ds_master.type=com.alibaba.druid.pool.DruidDataSource
sharding.jdbc.datasource.ds_master.driver-class-name=com.mysql.jdbc.Driver
sharding.jdbc.datasource.ds_master.url=jdbc:mysql://localhost:3306/ds_0?characterEncoding=utf-8
sharding.jdbc.datasource.ds_master.username=root
sharding.jdbc.datasource.ds_master.password=123456
# 分表配置
sharding.jdbc.config.sharding.tables.user.actual-data-nodes=ds_master.user_${0..3}
sharding.jdbc.config.sharding.tables.user.table-strategy.inline.sharding-column=id
sharding.jdbc.config.sharding.tables.user.table-strategy.inline.algorithm-expression=user_${id.longValue() % 4}
  • actual-data-nodes:真实数据节点,由数据源名 + 表名组成,以小数点分隔。多个表以逗号分隔,支持inline表达式。
  • table-strategy.inline.sharding-column:分片字段配置
  • table-strategy.inline.algorithm-expression:分片算法表达式

自定义分片算法

在1.x版本中,单分片算法是通过实现SingleKeyTableShardingAlgorithm,示例代码如下:

import java.util.Collection;
import java.util.LinkedHashSet; import com.dangdang.ddframe.rdb.sharding.api.ShardingValue;
import com.dangdang.ddframe.rdb.sharding.api.strategy.table.SingleKeyTableShardingAlgorithm;
import com.google.common.collect.Range; public class UserSingleKeyTableShardingAlgorithm implements SingleKeyTableShardingAlgorithm<Long> { public String doEqualSharding(Collection<String> availableTargetNames, ShardingValue<Long> shardingValue) {
for (String each : availableTargetNames) {
System.out.println(each+"\t"+shardingValue.getValue()+"\t"+shardingValue.getValue() % 4 );
if (each.endsWith(shardingValue.getValue() % 4 + "")) {
return each;
}
}
throw new IllegalArgumentException();
} public Collection<String> doInSharding(Collection<String> availableTargetNames, ShardingValue<Long> shardingValue) {
Collection<String> result = new LinkedHashSet<>(availableTargetNames.size());
for (Long value : shardingValue.getValues()) {
for (String tableName : availableTargetNames) {
if (tableName.endsWith(value % 4 + "")) {
result.add(tableName);
}
}
}
return result;
} public Collection<String> doBetweenSharding(Collection<String> availableTargetNames,
ShardingValue<Long> shardingValue) {
Collection<String> result = new LinkedHashSet<>(availableTargetNames.size());
Range<Long> range = (Range<Long>) shardingValue.getValueRange();
for (Long i = range.lowerEndpoint(); i <= range.upperEndpoint(); i++) {
for (String each : availableTargetNames) {
if (each.endsWith(i % 4 + "")) {
result.add(each);
}
}
}
return result;
} }

我们这边引入的Spring Boot Starter包是2.x的版本,在这个版本中,分片算法的接口有调整,我们需要用到标准分片策略StandardShardingStrategy。提供对SQL语句中的=, IN和BETWEEN AND的分片操作支持。StandardShardingStrategy只支持单分片键,提供PreciseShardingAlgorithm和RangeShardingAlgorithm两个分片算法。PreciseShardingAlgorithm是必选的,用于处理=和IN的分片。RangeShardingAlgorithm是可选的,用于处理BETWEEN AND分片,如果不配置RangeShardingAlgorithm,SQL中的BETWEEN AND将按照全库路由处理。

自定义一个单分片算法

import java.util.Collection;
import io.shardingjdbc.core.api.algorithm.sharding.PreciseShardingValue;
import io.shardingjdbc.core.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
/**
* 自定义分片算法
*
* @author yinjihuan
*
*/
public class MyPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long> { @Override
public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
for (String tableName : availableTargetNames) {
if (tableName.endsWith(shardingValue.getValue() % 4 + "")) {
return tableName;
}
}
throw new IllegalArgumentException();
} }

使用需要修改我们之前的配置

sharding.jdbc.config.sharding.tables.user.actual-data-nodes=ds_master.user_${0..3}
sharding.jdbc.config.sharding.tables.user.table-strategy.standard.sharding-column=id
sharding.jdbc.config.sharding.tables.user.table-strategy.standard.precise-algorithm-class-name=com.fangjia.sharding.MyPreciseShardingAlgorithm

源码参考:

https://github.com/yinjihuan/spring-cloud/tree/master/fangjia-sjdbc-sharding-table-springboot

参考代码中测试的代码也写好了,在Controller中,启动后通过调用接口的方式测试数据的添加和查询。

另外Sharding-Sphere 3.0.0.M3也发布了,新版本看点:

1.XA分布式事务

2.数据库治理模块增强

3.API部分调整

4.修复M2Bug

项目地址:

https://github.com/sharding-sphere/sharding-sphere/

https://gitee.com/sharding-sphere/sharding-sphere/

一个这么优秀的框架,这么靠谱的研发团队,大家赶紧学起来呀!

欢迎加入我的知识星球,一起交流技术,免费学习猿天地的课程(http://cxytiandi.com/course)

Spring Boot中整合Sharding-JDBC单库分表示例的更多相关文章

  1. 从零开始的Spring Boot(2、在Spring Boot中整合Servlet、Filter、Listener的方式)

    在Spring Boot中整合Servlet.Filter.Listener的方式 写在前面 从零开始的Spring Boot(1.搭建一个Spring Boot项目Hello World):http ...

  2. SpringBoot+Mybatis-Plus整合Sharding-JDBC5.1.1实现单库分表【全网最新】

    一.前言 小编最近一直在研究关于分库分表的东西,前几天docker安装了mycat实现了分库分表,但是都在说mycat的bug很多.很多人还是倾向于shardingsphere,其实他是一个全家桶,有 ...

  3. Sharding-JDBC:单库分表的实现

    剧情回顾 前面,我们一共学习了读写分离,垂直拆分,垂直拆分+读写分离.对应的文章分别如下: Sharding-JDBC:查询量大如何优化? Sharding-JDBC:垂直拆分怎么做? 通过上面的优化 ...

  4. Sharding-JDBC实现水平拆分-单库分表

    参考资料:猿天地   https://mp.weixin.qq.com/s/901rNhc4WhLCQ023zujRVQ 作者:尹吉欢 当单表的数量急剧上升,超过了1千万以上,这个时候就要对表进行水平 ...

  5. mycat 单库分表

    上次把mycat的读写分离搞定了,这次试下单库分表,顾名思义就是在一个库里把一个表拆分为多个 需要配置的配置文件为 schema.xml 配置内容如下 <!DOCTYPE mycat:schem ...

  6. Spring Boot中整合Sharding-JDBC读写分离示例

    在我<Spring Cloud微服务-全栈技术与案例解析>书中,第18章节分库分表解决方案里有对Sharding-JDBC的使用进行详细的讲解. 之前是通过XML方式来配置数据源,读写分离 ...

  7. spring boot:配置shardingsphere(sharding jdbc)使用druid数据源(druid 1.1.23 / sharding-jdbc 4.1.1 / mybatis / spring boot 2.3.3)

    一,为什么要使用druid数据源? 1,druid的优点 Druid是阿里巴巴开发的号称为监控而生的数据库连接池 它的优点包括: 可以监控数据库访问性能 SQL执行日志 SQL防火墙 但spring ...

  8. Spring boot项目集成Sharding Jdbc

    环境 jdk:1.8 framework: spring boot, sharding jdbc database: MySQL 搭建步骤 在pom 中加入sharding 依赖 <depend ...

  9. springboot with appache sharding 3.1 单库分表

    配置文件相关信息: #开发 server.port=7200 spring.application.name=BtspIsmpServiceOrderDev eureka.client.service ...

随机推荐

  1. SpringBoot 整合RabbitMQ错误记录

    1. 控制台报错:Exception in thread "main" java.io.IOException…… Caused by: com.rabbitmq.client.S ...

  2. IDEA设置方法参数列表类型自动提示

    默认情况下,IDEA的提示不够完全,可以通过以下设置,将提示功能打开的更完善. 效果如下面俩图所示

  3. java的递归异常—一个异常可能由另一个异常触发

    关键字: Caused by nested exception java.lang.reflect.InvocationTargetException: null at sun.reflect.Nat ...

  4. springboot拦截器拦了静态资源css,js,png,jpeg,svg等等静态资源

    1.在SpringBoot中自己写的拦截器,居然把静态资源也拦截了,导致了页面加载失败. package com.bie.config; import com.bie.component.MyLoca ...

  5. 【spring】自定义注解 custom annotation

    自定义注解 custom annotation 使用场景 类属性自动赋值. 验证对象属性完整性. 代替配置文件功能,像spring基于注解的配置. 可以生成文档,像java代码注释中的@see,@pa ...

  6. C#解析JSON数组

    方式一 第一步:使用前,需下载:Newtonsoft.Json.dll 没有的,请到我百度云盘下载 链接:https://pan.baidu.com/s/1JBkee4qhtW7XOyYFiGOL2Q ...

  7. 智能家居-3.基于esp8266的语音控制系统(软件篇)

    智能家居-1.基于esp8266的语音控制系统(开篇) 智能家居-2.基于esp8266的语音控制系统(硬件篇) 智能家居-3.基于esp8266的语音控制系统(软件篇) 赞赏支持 QQ:505645 ...

  8. Windows中将nginx添加到服务(转)

    下载安装nginx http://nginx.org/en/download.html 下载后解压到C盘 C:\nginx-1.14.0 添加服务 需要借助"Windows Service ...

  9. 修改源代码时不需要重启tomcat服务器

    我们在写JSP + Servlet 的时修改了Java代码就要重新启动服务器.十分麻烦. 为了解决这个问题我们可以将服务器改成debug 模式.就是按调试状态这样修改Java代码就不用再重新启动服务器 ...

  10. 简单使用:SpringBoot整合Redis

    1.导入依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...