1. 数据源DataSource接口

1
2
3
4
5
6
public interface DataSource  extends CommonDataSource, Wrapper {

Connection getConnection() throws SQLException;

Connection getConnection(String username, String password) throws SQLException;
}

img

图中 Druid 连接池实现了 DataSource 的两个核心接口(获取连接), 因此我们可以非常简单获取连接并执行 JDBC 操作。

img

img

2. shardingsphere-JDBC本质是一个数据源连接池

下图展示了 shardingsphere jdbc 4.X 源码:

img

和 Druid 一样,shardingsphere-JDBC 本质是一个数据源连接池 ,只不过它可以管理多个数据源,同时配置分片规则,当执行 SQL 时,根据分片规则,路由到相应分片,并执行,当然它的内部机制实现相比之下更复杂而已。

3. 使用shardingsphere-JDBC原生API编写一个入门例子

需求:一个库中有 2 个订单表,按照订单 id 取模,将数据路由到指定的表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
drop database if exists sj_ds0;
create database sj_ds0;
use sj_ds0;
drop table if exists t_order_0;
create table t_order_0(
order_id bigint not null primary key,
user_id bigint not null,
price bigint not null
);
drop table if exists t_order_1;
create table t_order_1(
order_id bigint not null primary key,
user_id bigint not null,
price bigint not null
);
drop table if exists t_user;
create table t_user(
id bigint not null primary key auto_increment,
name varchar(128) not null
);

img

演示代码如下:

img

代码逻辑流程:

1、配置真实数据源

img数据源 HashMap 的 key 是数据源的别名,在后面的分片规则里会用到。

2、 配置分表规则

img

首先,定义分表规则 ,逻辑表名叫 t_order , ds0.t_order_$->{0..1} 是 grovvy 表达式,它对应的真实表是 ds0.t_order_0, ds0.t_order_1 ,

接着,内置的分片算法,分片字段是 order_id , 规则是:orderId % 2的结果就是将orderId除以2所得的余数,它的取值范围是 0或 1 。

3、 将分表规则添加到分片规则列表

img

4、 配置属性

img

建议在调试/开发阶段输出分片执行日志,方便调试。

5、 创建数据源

img

6、 获取连接,测试向t_order表插入8条数据,8条数据会分散到2个表

img

启动应用后,控制台显示如下:

img

查看数据库表,发现 8 条数据均匀分布到两张订单表里。

img


本站由 卡卡龙 使用 Stellar 1.27.0 主题创建

本站访问量 次. 本文阅读量 次.