一、簡介
1、是輕量級的java架構,是增強版的JDBC驅動
2、Sharding-JDBC
(1)主要目的是:簡化對分庫分表之後資料相關操作
Sharding-JDBC是當當網研發的開源分布式資料庫中間件,從 3.0 開始Sharding-JDBC被包含在 Sharding-Sphere中,之後該項目進入Apache孵化器,
4.0版本之後的版本為Apache版本。
Sharding-JDBC是ShardingSphere的第一個産品,也是ShardingSphere的前身。 它定位為輕量級Java架構,在Java的JDBC層提供的額外服務。
它使用用戶端直連資料庫,以jar包形式提供服務,無需額外部署和依賴,可了解為增強版的JDBC驅動,完全相容JDBC和各種ORM架構。

Sharding-JDBC的核心功能為資料分片和讀寫分離,通過Sharding-JDBC,應用可以透明的使用jdbc通路已經分庫分表、讀寫分離的多個資料源,
而不用關心資料源的數量以及資料如何分布。
1. 适用于任何基于JDBC的ORM架構,如:JPA, Hibernate, Mybatis, Spring JDBC Template或直接使用JDBC。
2. 支援任何第三方的資料庫連接配接池,如:DBCP, C3P0, BoneCP, Druid, HikariCP等。
3. 支援任意實作JDBC規範的資料庫。目前支援MySQL,Oracle,SQLServer,PostgreSQL以及任何遵循SQL92标準的資料庫。
二、Sharding-JDBC實作水準分表
2.1 搭建環境
Sharding-JDBC-水準分表源碼
(1)技術:SpringBoot 2.2.1+ MyBatisPlus + Sharding-JDBC + Druid連接配接池
(2)建立SpringBoot工程
(3)修改工程SpringBoot版本 2.2.1
(4) 引入需要的依賴
2.1.1 建立SpringBoot工程
2.1.2 修改工程SpringBoot版本 2.2.1
2.1.3 引入相關依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.20</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.0.0-RC1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
2.2 安裝水準分表的方式,建立資料庫和資料庫表
1. 建立資料庫course_db
2. 在資料庫建立兩張表course_1和course_2
3. 約定規則:如果添加課程id是偶數把資料添加course_1,如果奇數添加到course_2
1.建表語句
CREATE DATABASE `course_db` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';
DROP TABLE IF EXISTS `course_1`;
create table course_1 (
cid bigint(20) primary key comment '課程id',
cname varchar(50) not null comment '課程名稱',
user_id bigint(20) not null comment '使用者',
cstatus varchar(10) not null comment '狀态'
)
DROP TABLE IF EXISTS `course_2`;
create table course_2 (
cid bigint(20) primary key comment '課程id',
cname varchar(50) not null comment '課程名稱',
user_id bigint(20) not null comment '使用者',
cstatus varchar(10) not null comment '狀态'
)
2.3 編寫代碼實作對分庫分表後資料的操作
1. 建立實體類,mapper
2.4 配置Sharding-JDBC分片政策
2.4.1 在項目application.properties配置檔案中進行配置
# shardingjdbc分片政策
# 配置資料源,給資料源起名稱
spring.shardingsphere.datasource.names=m1
# 配置資料源具體内容,包含連接配接池,驅動,位址,使用者名和密碼
spring.shardingsphere.datasource.m1.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m1.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.m1.url=jdbc:mysql://localhost:3306/course_db?serverTimezone=GMT%2B8
spring.shardingsphere.datasource.m1.username=root
spring.shardingsphere.datasource.m1.password=root
# 指定course表分布情況,配置表在哪個資料庫裡面,表名稱都是什麼 m1.course_1, m1.course_2
spring.shardingsphere.sharding.tables.course.actual-data-nodes=m1.course_$->{1..2}
# 指定course表裡面主鍵cid 生成政策 SNOWFLAKE 雪花算法
spring.shardingsphere.sharding.tables.course.key-generator.column=cid
spring.shardingsphere.sharding.tables.course.key-generator.type=SNOWFLAKE
# 指定表分片政策 約定cid值偶數添加到course_1表,如果cid是奇數添加到course_2表
spring.shardingsphere.sharding.tables.course.table-strategy.inline.sharding-column=cid
spring.shardingsphere.sharding.tables.course.table-strategy.inline.algorithm-expression=course_$->{cid % 2 + 1}
# 打開sql輸出日志
spring.shardingsphere.props.sql.show=true
2.5 編寫測試代碼
@SpringBootTest
class ShardingjdbcdemoApplicationTests {
// 注入mapper
@Autowired
private CourseMapper courseMapper;
// 添加課程的方法
@Test
void addCourse() {
for (int i = 0; i <= 10; i++) {
Course course = new Course();
course.setCname("java" + i);
course.setUserId(100L);
course.setCstatus("Normal" + i);
courseMapper.insert(course);
}
}
// 查詢課程的方法
@Test
public void findCourse() {
QueryWrapper<Course> wrapper = new QueryWrapper<>();
wrapper.eq("cid", 636274552548098048L);
Course course = courseMapper.selectOne(wrapper);
System.out.println(course);
}
}
(1)上面測試代碼執行,報錯了
(2)解決方案,在配置檔案中添加一行配置
三、Sharding-JDBC水準分庫
Sharding-JDBC-水準分庫源碼
3.1 需求分析
3.2 建立資料庫和表
CREATE DATABASE `edu_db_1` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';
CREATE DATABASE `edu_db_2` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';
DROP TABLE IF EXISTS `course_1`;
create table course_1 (
cid bigint(20) primary key comment '課程id',
cname varchar(50) not null comment '課程名稱',
user_id bigint(20) not null comment '使用者',
cstatus varchar(10) not null comment '狀态'
);
DROP TABLE IF EXISTS `course_2`;
create table course_2 (
cid bigint(20) primary key comment '課程id',
cname varchar(50) not null comment '課程名稱',
user_id bigint(20) not null comment '使用者',
cstatus varchar(10) not null comment '狀态'
)
3.3 在SpringBoot配置檔案配置資料庫分片規則
# shardingjdbc分片政策
# 配置資料源,給資料源起名稱
# 水準分庫,配置兩個資料源
spring.shardingsphere.datasource.names=m1,m2
# 配置第一個資料源具體内容,包含連接配接池,驅動,位址,使用者名和密碼
spring.shardingsphere.datasource.m1.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m1.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.m1.url=jdbc:mysql://localhost:3306/edu_db_1?serverTimezone=GMT%2B8
spring.shardingsphere.datasource.m1.username=root
spring.shardingsphere.datasource.m1.password=root
# 配置第二個資料源具體内容,包含連接配接池,驅動,位址,使用者名和密碼
spring.shardingsphere.datasource.m2.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m2.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.m2.url=jdbc:mysql://localhost:3306/edu_db_2?serverTimezone=GMT%2B8
spring.shardingsphere.datasource.m2.username=root
spring.shardingsphere.datasource.m2.password=root
# 指定資料庫分布情況,資料庫裡面表分布情況
# m1 m2 course_1 course_2
spring.shardingsphere.sharding.tables.course.actual-data-nodes=m$->{1..2}.course_$->{1..2}
# 指定course表裡面主鍵cid 生成政策 SNOWFLAKE 雪花算法
spring.shardingsphere.sharding.tables.course.key-generator.column=cid
spring.shardingsphere.sharding.tables.course.key-generator.type=SNOWFLAKE
# 指定表分片政策 約定cid值偶數添加到course_1表,如果cid是奇數添加到course_2表
spring.shardingsphere.sharding.tables.course.table-strategy.inline.sharding-column=cid
spring.shardingsphere.sharding.tables.course.table-strategy.inline.algorithm-expression=course_$->{cid % 2 + 1}
# 指定資料庫分片政策 約定user_id是偶數添加m1,是奇數添加m2,default預設所有表
#spring.shardingsphere.sharding.default-database-strategy.inline.sharding-column=user_id
#spring.shardingsphere.sharding.default-database-strategy.inline.algorithm-expression=m$->{user_id % 2 + 1}
# 僅針對course表
spring.shardingsphere.sharding.tables.course.database-strategy.inline..sharding-column=user_id
spring.shardingsphere.sharding.tables.course.database-strategy.inline.algorithm-expression=m$->{user_id % 2 + 1}
# 打開sql輸出日志
spring.shardingsphere.props.sql.show=true
# 一個實體類對應兩張表,覆寫
spring.main.allow-bean-definition-overriding=true
3.4 編寫測試方法
@SpringBootTest
class ShardingjdbcdemoApplicationTests {
// 注入mapper
@Autowired
private CourseMapper courseMapper;
//======================測試水準分庫=====================
// 添加操作
@Test
public void addCourseDb() {
Course course = new Course();
course.setCname("javademo1");
//分庫根據user_id
course.setUserId(222L);
course.setCstatus("Normal1");
courseMapper.insert(course);
}
// 查詢操作
@Test
public void findCourseDb() {
QueryWrapper<Course> wrapper = new QueryWrapper<>();
// 設定userid值
wrapper.eq("user_id",111L);
// 設定cid值
wrapper.eq("cid",636298809789382657L);
Course course = courseMapper.selectOne(wrapper);
System.out.println(course);
}
}
四、Sharding-JDBC實作垂直分庫
Sharding-JDBC-垂直分庫源碼
4.1 需求分析
4.2 建立資料庫和表
CREATE DATABASE `user_db` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';
DROP TABLE IF EXISTS `t_user`;
create table t_user (
user_id bigint(20) primary key comment '使用者id',
user_name varchar(50) not null comment '使用者名字',
ustatus varchar(10) not null comment '使用者狀态'
);
4.3 編寫操作代碼
4.3.1 建立user實體類和mapper
@Data
@TableName(value = "t_user") // 指定對應表
public class User {
private Long userId;
private String userName;
private String uStatus;
}
Sharding-JDBC 實作水準切分與垂直切分一、簡介二、Sharding-JDBC實作水準分表三、Sharding-JDBC水準分庫四、Sharding-JDBC實作垂直分庫五、Sharding-JDBC操作公共表
4.3.2 配置垂直分庫政策
* 在application.properties進行配置
# shardingjdbc分片政策
# 配置資料源,給資料源起名稱
# 水準分庫,配置兩個資料源
spring.shardingsphere.datasource.names=m0,m1,m2
# 配置第一個資料源具體内容,包含連接配接池,驅動,位址,使用者名和密碼
spring.shardingsphere.datasource.m1.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m1.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.m1.url=jdbc:mysql://localhost:3306/edu_db_1?serverTimezone=GMT%2B8
spring.shardingsphere.datasource.m1.username=root
spring.shardingsphere.datasource.m1.password=root
# 配置第二個資料源具體内容,包含連接配接池,驅動,位址,使用者名和密碼
spring.shardingsphere.datasource.m2.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m2.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.m2.url=jdbc:mysql://localhost:3306/edu_db_2?serverTimezone=GMT%2B8
spring.shardingsphere.datasource.m2.username=root
spring.shardingsphere.datasource.m2.password=root
#-------------------垂直分庫-------------------
# 配置第三個資料源具體内容,包含連接配接池,驅動,位址,使用者名和密碼
spring.shardingsphere.datasource.m0.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m0.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.m0.url=jdbc:mysql://localhost:3306/user_db?serverTimezone=GMT%2B8
spring.shardingsphere.datasource.m0.username=root
spring.shardingsphere.datasource.m0.password=root
# 配置user_db資料庫裡面t_user 專庫專表
# 指定資料庫分布情況,資料庫裡面表分布情況
spring.shardingsphere.sharding.tables.t_user.actual-data-nodes=m$->{0}.t_user
# 指定t_user表裡面主鍵user_id 生成政策 SNOWFLAKE 雪花算法
spring.shardingsphere.sharding.tables.t_user.key-generator.column=user_id
spring.shardingsphere.sharding.tables.t_user.key-generator.type=SNOWFLAKE
# 指定表分片政策 約定user_id值添加到t_user表
spring.shardingsphere.sharding.tables.t_user.table-strategy.inline.sharding-column=user_id
spring.shardingsphere.sharding.tables.t_user.table-strategy.inline.algorithm-expression=t_user
#-------------------水準分庫分表-------------------
# 指定資料庫分布情況,資料庫裡面表分布情況
# m1 m2 course_1 course_2
spring.shardingsphere.sharding.tables.course.actual-data-nodes=m$->{1..2}.course_$->{1..2}
# 指定course表裡面主鍵cid 生成政策 SNOWFLAKE 雪花算法
spring.shardingsphere.sharding.tables.course.key-generator.column=cid
spring.shardingsphere.sharding.tables.course.key-generator.type=SNOWFLAKE
# 指定表分片政策 約定cid值偶數添加到course_1表,如果cid是奇數添加到course_2表
spring.shardingsphere.sharding.tables.course.table-strategy.inline.sharding-column=cid
spring.shardingsphere.sharding.tables.course.table-strategy.inline.algorithm-expression=course_$->{cid % 2 + 1}
# 指定資料庫分片政策 約定user_id是偶數添加m1,是奇數添加m2,default預設所有表
#spring.shardingsphere.sharding.default-database-strategy.inline.sharding-column=user_id
#spring.shardingsphere.sharding.default-database-strategy.inline.algorithm-expression=m$->{user_id % 2 + 1}
# 僅針對course表
spring.shardingsphere.sharding.tables.course.database-strategy.inline..sharding-column=user_id
spring.shardingsphere.sharding.tables.course.database-strategy.inline.algorithm-expression=m$->{user_id % 2 + 1}
#-------------------公共配置-------------------
# 打開sql輸出日志
spring.shardingsphere.props.sql.show=true
# 一個實體類對應兩張表,覆寫
spring.main.allow-bean-definition-overriding=true
4.3.3 編寫測試代碼
@SpringBootTest
class ShardingjdbcdemoApplicationTests {
// 注入mapper
@Autowired
private UserMapper userMapper;
//======================測試垂直分庫==================
// 添加操作
@Test
public void addUserDb() {
User user = new User();
user.setUserName("lucymary");
user.setUstatus("a");
userMapper.insert(user);
}
// 查詢操作
@Test
public void findUserDb() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
// 設定userid值
wrapper.eq("user_id",465508031619137537L);
User user = userMapper.selectOne(wrapper);
System.out.println(user);
}
}
五、Sharding-JDBC操作公共表
Sharding-JDBC-公共表源碼
5.1 公共表
1、公共表
(1)存儲固定資料的表,表資料很少發生變化,查詢時候經常進行關聯
(2)在每個資料庫中建立出相同結構公共表
5.2 在多個資料庫都建立相同結構公共表
DROP TABLE IF EXISTS `t_udict`;
create table t_udict (
dictid bigint(20) primary key comment '字典id',
ustatus varchar(100) not null comment '使用者狀态',
uvalue varchar(1000) not null comment '值'
);
5.3 在項目配置檔案application.properties進行公共表配置
#-------------------公共表-------------------
# 配置公共表
spring.shardingsphere.sharding.broadcast-tables=t_udict
spring.shardingsphere.sharding.tables.t_udict.key-generator.column=dictid
spring.shardingsphere.sharding.tables.t_udict.key-generator.type=SNOWFLAKE
5.4 編寫測試代碼
(1)建立新實體類和mapper
@Data
@TableName(value = "t_udict")
public class Udict {
private Long dictid;
private String ustatus;
private String uvalue;
}
(2)編寫添加和删除方法進行測試
@SpringBootTest
class ShardingjdbcdemoApplicationTests {
// 注入mapper
@Autowired
private UdictMapper udictMapper;
//======================測試公共表===================
// 添加操作
@Test
public void addDict() {
Udict udict = new Udict();
udict.setUstatus("a");
udict.setUvalue("已啟用");
udictMapper.insert(udict);
}
// 删除操作
@Test
public void deleteDict() {
QueryWrapper<Udict> wrapper = new QueryWrapper<>();
//設定userid值
wrapper.eq("dictid",465191484111454209L);
udictMapper.delete(wrapper);
}
}
視訊教程