服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Spring Boot 集成 Sharding-JDBC + Mybatis-Plus 实现分库分表功能

Spring Boot 集成 Sharding-JDBC + Mybatis-Plus 实现分库分表功能

2020-08-27 12:41Java技术小吴 Java教程

这篇文章主要介绍了Spring Boot 集成 Sharding-JDBC + Mybatis-Plus 实现分库分表功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

一、 Sharding-jdbc简介

Sharding-jdbc是开源的数据库操作中间件;定位为轻量级Java框架,在Java的JDBC层提供的额外服务。它使用客户端直连数据库,以jar包形式提供服务,无需额外部署和依赖,可理解为增强版的JDBC驱动,完全兼容JDBC和各种ORM框架。

官方文档地址:https://shardingsphere.apache.org/document/current/cn/overview/

本文demo实现了分库分表功能。如有错误,欢迎各位在评论中指出。不胜感激!

二、项目结构

 

首先创建一个一般的Spring boot项目,项目采用三层架构,结构图如下:

Spring Boot 集成 Sharding-JDBC + Mybatis-Plus 实现分库分表功能

POM.xml文件如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?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>

实体类以书本为例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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: 书籍是实体类
 * @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;
}

开放保存和查询两个接口,代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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> {
}

创建数据库表,DDL语句如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
创建数据库表数据
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:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
> 推荐一个艿艿写的 3000+ Star 的 SpringCloud Alibaba 电商开源项目的仓库:<https://github.com/YunaiV/onemall>
 
# 数据源 db0,db1,db2
sharding.jdbc.datasource.names=db0,db1,db2
# 第一个数据库
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
 
# 第二个数据库
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
 
# 第三个数据库
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
 
# 水平拆分的数据库(表) 配置分库 + 分表策略 行表达式分片策略
# 分库策略
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
# 分片算法表达式
sharding.jdbc.config.sharding.tables.book.table-strategy.inline.algorithm-expression=book_$->{count % 3}
 
# 主键 UUID 18位数 如果是分布式还要进行一个设置 防止主键重复
#sharding.jdbc.config.sharding.tables.user.key-generator-column-name=id
 
# 打印执行的数据库以及语句
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 如各位觉得有帮助的话,还请给个star鼓励鼓励博主,谢谢!

三、总结

 

分库分表实现按照官方文档做一个demo是第一步,如需深入还需要研究源码,研究架构,研究思想;此文仅作为入门demo搭建指南,如需深入理解,还请移步至官方文档。

到此这篇关于Spring Boot 集成 Sharding-JDBC + Mybatis-Plus 实现分库分表功能的文章就介绍到这了,更多相关Spring Boot实现分库分表内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_48673251/article/details/108250049

延伸 · 阅读

精彩推荐