聲明
-
本文會基於
Springboot + mybatis + shardingsphere + mysql5.6 + druid
進行實戰講解 -
本文的實戰內容爲分表、以及數據分片, 不涉及分庫, 讀寫分離之類的
-
本文不會介紹
shardingsphere
的歷史、概念以及分庫分表的相關理論 -
本文采用的
shardingsphere
版本是 5.0.0-alpha, 具體見 pom 文件 -
本文涉及的源碼請參考 碼雲地址
-
如果看 官方文檔 時, 請選對版本 !!!
正文
實現目標
我們有一張邏輯用戶表 user_info
, 我們把它水平拆分成 user_info0
和 user_info1
兩張物理表 當我們往用戶表插數據時, 數據會按照一定的規則(根據id取模), 寫入到其中一張 user_info 表中.
準備工作
1. 數據庫表
create database miaosha;
DROP TABLE IF EXISTS `user_info0`;
CREATE TABLE `user_info0` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_label` varchar(32) COLLATE utf8_bin DEFAULT NULL,
`username` varchar(64) COLLATE utf8_bin DEFAULT NULL,
`email` varchar(64) COLLATE utf8_bin DEFAULT NULL,
`phone` varchar(64) COLLATE utf8_bin DEFAULT NULL,
`password` varchar(128) COLLATE utf8_bin NOT NULL,
`active` tinyint(4) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
DROP TABLE IF EXISTS `user_info1`;
CREATE TABLE `user_info1` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_label` varchar(32) COLLATE utf8_bin DEFAULT NULL,
`username` varchar(64) COLLATE utf8_bin DEFAULT NULL,
`email` varchar(64) COLLATE utf8_bin DEFAULT NULL,
`phone` varchar(64) COLLATE utf8_bin DEFAULT NULL,
`password` varchar(128) COLLATE utf8_bin NOT NULL,
`active` tinyint(4) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
2. pom 依賴
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.nimo</groupId>
<artifactId>shardingsphere-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>shardingsphere-demo</name>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- shardingsphere -->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.0.0-alpha</version>
</dependency>
<!-- 阿里數據源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
3. application.yml
再次強調下, 本文采用的 shardingsphere 版本是 5.0.0-alpha. 不同版本配置會有差異.
填寫配置文件時,一定要小心, 坑死了; 不信你不配置 com.alibaba.druid.pool.DruidDataSource
試試,
或者你用默認的數據源替換試試 om.zaxxer.hikari.HikariDataSource
server:
port: 8777
spring:
shardingsphere:
props:
sql-show: true
datasource:
names: ds0
# 注意這裏的數據源配置用的是 druid
common:
type: com.alibaba.druid.pool.DruidDataSource
ds0:
url: jdbc:mysql://127.0.0.1:3306/miaosha?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2b8
username: root
password: '123456'
driver-class-name: com.mysql.cj.jdbc.Driver
rules:
sharding:
key-generators:
# 此處必須要配置,否則會導致報錯,因爲shardingsphere-jdbc-core-spring-boot-starter需要加載此項配置,官網的demo例子有錯
snowflake:
type: SNOWFLAKE
props:
worker-id: 123
sharding-algorithms:
table-inline:
type: INLINE
props:
# 不要漏掉 $ 或 ->
algorithm-expression: user_info$->{id % 2}
tables:
user_info:
# 配置 user_info 的分表的規則
actual-data-nodes: ds0.user_info$->{0..1}
table-strategy:
standard:
sharding-column: id
sharding-algorithm-name: table-inline
enabled: true
mybatis:
typeAliasesPackage: com.nimo.shardingspheredemo.entity
mapperLocations: classpath:mapper/*.xml
4. 主要代碼
// sql
<insert id="addUser" parameterType="com.nimo.shardingdemo.entity.UserInfo">
insert into user_info(id, username, password) values (#{id}, #{username}, #{password})
</insert>
// 新增一個用戶信息
@PostMapping("userinfo")
public Object addUserInfo(@RequestBody UserInfo userInfo) {
return userInfoMapper.addUser(userInfo);
}
5. 測試命令
curl -X POST --location "http://localhost:8777/userinfo" \
-H "Content-Type: application/json" \
-d "{
\"id\": 18,
\"username\": \"wangbadan\",
\"password\": \"123456\"
}"
問題
我們創建表時設置的 主鍵id 是自增的, 理論上是不用傳的, 但是我們往表中插數據, 是根據 主鍵id 取模 來決定具體往哪張表中插的. 所以這個主鍵 id 此時必須得有.
另外, 如果我們的服務有多個, 那麼這個 id 如何生成?
如何解決
首先把 sql 改寫爲如下方式:
// sql
<insert id="addUser" parameterType="com.nimo.shardingdemo.entity.UserInfo">
insert into user_info(username, password)
values ( #{username}, #{password})
</insert>
然後在原有配置的基礎上, 追加如下配置信息(通過雪花算法生成id)
spring:
shardingsphere:
rules:
sharding:
tables:
user_info:
key-generate-strategy:
key-generator-name: snowflake
column: id
總結
本文強調的是 分表, 分片 的實戰 demo 配置, 後面會逐漸更新 分庫、讀寫分離 的實戰 demo, 跟之前的 Spring Secutiry
的實戰教程一樣, 講究循序漸進.