一诈铛、 Sharding-jdbc簡介
Sharding-jdbc是開源的數(shù)據(jù)庫操作中間件勿璃;定位為輕量級Java框架颊埃,在Java的JDBC層提供的額外服務(wù)仁讨。它使用客戶端直連數(shù)據(jù)庫,以jar包形式提供服務(wù),無需額外部署和依賴猬错,可理解為增強(qiáng)版的JDBC驅(qū)動窗看,完全兼容JDBC和各種ORM框架。
官方文檔地址:https://shardingsphere.apache.org/document/current/cn/overview/
本文demo實(shí)現(xiàn)了分庫分表功能倦炒。
二显沈、項(xiàng)目結(jié)構(gòu)
首先創(chuàng)建一個一般的Spring boot項(xiàng)目,項(xiàng)目采用三層架構(gòu)析校,結(jié)構(gòu)圖如下:項(xiàng)目目錄結(jié)構(gòu)圖 pom.xml文件如下:
<?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 http://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.1.6.RELEASE</version>
? ? ? ? <relativePath/> <!-- lookup parent from repository -->
? ? </parent>
? ? <groupId>com.macky</groupId>
? ? <artifactId>spring-boot-shardingjdbc</artifactId>
? ? <version>0.0.1-SNAPSHOT</version>
? ? <name>spring-boot-shardingjdbc</name>
? ? <description>Demo project for spring-boot-shardingjdbc</description>
? ? <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.springframework.boot</groupId>
? ? ? ? ? ? <artifactId>spring-boot-starter-test</artifactId>
? ? ? ? ? ? <scope>test</scope>
? ? ? ? </dependency>
? ? ? ? <!--mysql-->
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>mysql</groupId>
? ? ? ? ? ? <artifactId>mysql-connector-java</artifactId>
? ? ? ? ? ? <scope>runtime</scope>
? ? ? ? </dependency>
? ? ? ? <!--Mybatis-Plus-->
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>com.baomidou</groupId>
? ? ? ? ? ? <artifactId>mybatis-plus-boot-starter</artifactId>
? ? ? ? ? ? <version>3.1.1</version>
? ? ? ? </dependency>
? ? ? ? <!--shardingsphere start-->
? ? ? ? <!-- for spring boot -->
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>io.shardingsphere</groupId>
? ? ? ? ? ? <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
? ? ? ? ? ? <version>3.1.0</version>
? ? ? ? </dependency>
? ? ? ? <!-- for spring namespace -->
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>io.shardingsphere</groupId>
? ? ? ? ? ? <artifactId>sharding-jdbc-spring-namespace</artifactId>
? ? ? ? ? ? <version>3.1.0</version>
? ? ? ? </dependency>
? ? ? ? <!--shardingsphere end-->
? ? ? ? <!--lombok-->
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>org.projectlombok</groupId>
? ? ? ? ? ? <artifactId>lombok</artifactId>
? ? ? ? </dependency>
? ? </dependencies>
? ? <build>
? ? ? ? <plugins>
? ? ? ? ? ? <plugin>
? ? ? ? ? ? ? ? <groupId>org.springframework.boot</groupId>
? ? ? ? ? ? ? ? <artifactId>spring-boot-maven-plugin</artifactId>
? ? ? ? ? ? </plugin>
? ? ? ? </plugins>
? ? </build>
</project>
實(shí)體類以書本為例:
package com.macky.springbootshardingjdbc.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import groovy.transform.EqualsAndHashCode;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* @author Macky
* @Title class Book
* @Description: 書籍是實(shí)體類
* @date 2019/7/13 15:23
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("book")
public class Book extends Model<Book> {
? ? private int id;
? ? private String name;
? ? private int count;
}
開放保存和查詢兩個接口,代碼如下:
package com.macky.springbootshardingjdbc.controller;
import com.macky.springbootshardingjdbc.entity.Book;
import com.macky.springbootshardingjdbc.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author Macky
* @Title class BookController
* @Description: TODO
* @date 2019/7/12 20:53
*/
@RestController
public class BookController {
? ? @Autowired
? ? BookService bookService;
? ? @RequestMapping(value = "/book", method = RequestMethod.GET)
? ? public List<Book> getItems(){
? ? ? ? return bookService.getBookList();
? ? }
? ? @RequestMapping(value = "/book",method = RequestMethod.POST)
? ? public Boolean saveItem(Book book){
? ? ? ? return bookService.save(book);
? ? }
}
BookServiceImpl.java
package com.macky.springbootshardingjdbc.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.macky.springbootshardingjdbc.entity.Book;
import com.macky.springbootshardingjdbc.mapper.BookMapper;
import com.macky.springbootshardingjdbc.service.BookService;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author Macky
* @Title class BookServiceImpl
* @Description: TODO
* @date 2019/7/12 20:47
*/
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
? ? @Override
? ? public List<Book> getBookList() {
? ? ? ? return baseMapper.selectList(Wrappers.<Book>lambdaQuery());
? ? }
? ? @Override
? ? public boolean save(Book book) {
? ? ? ? return super.save(book);
? ? }
}
BookMapper.java
package com.macky.springbootshardingjdbc.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.macky.springbootshardingjdbc.entity.Book;
/**
* @author Macky
* @Title class BookMapper
* @Description: TODO
* @date 2019/7/12 20:46
*/
public interface BookMapper extends BaseMapper<Book> {
}
創(chuàng)建數(shù)據(jù)庫表铜涉,DDL語句如下:
#創(chuàng)建數(shù)據(jù)庫表數(shù)據(jù)
CREATE DATABASE IF NOT EXISTS `db0`;
USE `db0`;
DROP TABLE IF EXISTS `book_0`;
CREATE TABLE `book_0` (
? ? `id` INT ( 11 ) NOT NULL,
? ? `name` VARCHAR ( 255 ) DEFAULT NULL,
? ? `count` INT ( 11 ) DEFAULT NULL,
? ? PRIMARY KEY ( `id` )
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;
DROP TABLE IF EXISTS `book_1`;
CREATE TABLE `book_1` (
? ? `id` INT ( 11 ) NOT NULL,
? ? `name` VARCHAR ( 255 ) DEFAULT NULL,
? ? `count` INT ( 11 ) DEFAULT NULL,
? ? PRIMARY KEY ( `id` )
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;
CREATE DATABASE IF NOT EXISTS `db1`;
USE `db1`;
DROP TABLE IF EXISTS `book_0`;
CREATE TABLE `book_0` (
? ? `id` INT ( 11 ) NOT NULL,
? ? `name` VARCHAR ( 255 ) DEFAULT NULL,
? ? `count` INT ( 11 ) DEFAULT NULL,
? ? PRIMARY KEY ( `id` )
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;
DROP TABLE IF EXISTS `book_1`;
CREATE TABLE `book_1` (
? ? `id` INT ( 11 ) NOT NULL,
? ? `name` VARCHAR ( 255 ) DEFAULT NULL,
? ? `count` INT ( 11 ) DEFAULT NULL,
? ? PRIMARY KEY ( `id` )
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;
CREATE DATABASE IF NOT EXISTS `db2`;
USE `db2`;
DROP TABLE IF EXISTS `book_0`;
CREATE TABLE `book_0` (
? ? `id` INT ( 11 ) NOT NULL,
? ? `name` VARCHAR ( 255 ) DEFAULT NULL,
? ? `count` INT ( 11 ) DEFAULT NULL,
? ? PRIMARY KEY ( `id` )
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;
DROP TABLE IF EXISTS `book_1`;
CREATE TABLE `book_1` (
? ? `id` INT ( 11 ) NOT NULL,
? ? `name` VARCHAR ( 255 ) DEFAULT NULL,
? ? `count` INT ( 11 ) DEFAULT NULL,
? ? PRIMARY KEY ( `id` )
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;
配置分庫分表策略application.properties:
# 數(shù)據(jù)源 db0,db1,db2
sharding.jdbc.datasource.names=db0,db1,db2
# 第一個數(shù)據(jù)庫
sharding.jdbc.datasource.db0.type=com.zaxxer.hikari.HikariDataSource
sharding.jdbc.datasource.db0.driver-class-name=com.mysql.cj.jdbc.Driver
sharding.jdbc.datasource.db0.jdbc-url=jdbc:mysql://localhost:3306/db0?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
sharding.jdbc.datasource.db0.username=root
sharding.jdbc.datasource.db0.password=Aa123456
# 第二個數(shù)據(jù)庫
sharding.jdbc.datasource.db1.type=com.zaxxer.hikari.HikariDataSource
sharding.jdbc.datasource.db1.driver-class-name=com.mysql.cj.jdbc.Driver
sharding.jdbc.datasource.db1.jdbc-url=jdbc:mysql://localhost:3306/db1?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
sharding.jdbc.datasource.db1.username=root
sharding.jdbc.datasource.db1.password=Aa123456
# 第三個數(shù)據(jù)庫
sharding.jdbc.datasource.db2.type=com.zaxxer.hikari.HikariDataSource
sharding.jdbc.datasource.db2.driver-class-name=com.mysql.cj.jdbc.Driver
sharding.jdbc.datasource.db2.jdbc-url=jdbc:mysql://localhost:3306/db2?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
sharding.jdbc.datasource.db2.username=root
sharding.jdbc.datasource.db2.password=Aa123456
# 水平拆分的數(shù)據(jù)庫(表) 配置分庫 + 分表策略 行表達(dá)式分片策略
# 分庫策略
sharding.jdbc.config.sharding.default-database-strategy.inline.sharding-column=id
sharding.jdbc.config.sharding.default-database-strategy.inline.algorithm-expression=db$->{id % 3}
# 分表策略 其中book為邏輯表 分表主要取決于id行
sharding.jdbc.config.sharding.tables.book.actual-data-nodes=db$->{0..2}.book_$->{0..2}
sharding.jdbc.config.sharding.tables.book.table-strategy.inline.sharding-column=count
# 分片算法表達(dá)式
sharding.jdbc.config.sharding.tables.book.table-strategy.inline.algorithm-expression=book_$->{count % 3}
# 主鍵 UUID 18位數(shù) 如果是分布式還要進(jìn)行一個設(shè)置 防止主鍵重復(fù)
#sharding.jdbc.config.sharding.tables.user.key-generator-column-name=id
# 打印執(zhí)行的數(shù)據(jù)庫以及語句
sharding.jdbc.config.props..sql.show=true
spring.main.allow-bean-definition-overriding=true
#讀寫分離
sharding.jdbc.datasource.dsmaster =
接口測試使用postman
示例:GET請求------>http://localhost:8080/book POST請求:------->http://localhost:8080/book?id=1&name=java編程思想&count=8
demo的github地址:https://github.com/Macky-He/spring-boot--shardingsphere-examples?
三智玻、總結(jié)
分庫分表實(shí)現(xiàn)按照官方文檔做一個demo是第一步,如需深入還需要研究源碼芙代,研究架構(gòu)吊奢,研究思想;此文僅作為入門demo搭建指南纹烹,如需深入理解页滚,還請移步至官方文檔,
官方文檔:https://shardingsphere.apache.org/document/current/cn/manual/sharding-jdbc/usage/sharding/