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

文章目录

  • Sharding-JDBC简介
  • 项目准备
  • 代码编写

Sharding-JDBC简介

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

项目准备

Spring Boot 之集成Sharding-JDBC+ Mybatis-Plus实现分库分表_第1张图片
POM.xml文件如下:


<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.1.13.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.demogroupId>
    <artifactId>spring-boot--shardingsphere-demoartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>spring-boot--shardingsphere-demoname>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.42version>
            <scope>runtimescope>
        dependency>
        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.1.1version>
        dependency>
        
        
        <dependency>
            <groupId>io.shardingspheregroupId>
            <artifactId>sharding-jdbc-spring-boot-starterartifactId>
            <version>3.1.0version>
        dependency>
        
        <dependency>
            <groupId>io.shardingspheregroupId>
            <artifactId>sharding-jdbc-spring-namespaceartifactId>
            <version>3.1.0version>
        dependency>
        

        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>

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

#创建数据库表数据
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;
DROP TABLE IF EXISTS `book_2`;
CREATE TABLE `book_2` (
	`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;
DROP TABLE IF EXISTS `book_2`;
CREATE TABLE `book_2` (
	`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;
DROP TABLE IF EXISTS `book_2`;
CREATE TABLE `book_2` (
	`id` INT ( 11 ) NOT NULL,
	`name` VARCHAR ( 255 ) DEFAULT NULL,
	`count` INT ( 11 ) DEFAULT NULL,
	PRIMARY KEY ( `id` ) 
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;

代码编写

实体类:

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("book")
public class Book extends Model<Book> {
    private int id;
    private String name;
    private int count;
}

BookMapper.java

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.demo.entity.Book;

public interface BookMapper extends BaseMapper<Book> {
}

BookServiceImpl.java

public interface BookService {
    List<Book> getBookList();
    boolean save(Book book);
}

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.entity.Book;
import com.demo.mapper.BookMapper;
import com.demo.service.BookService;
import org.springframework.stereotype.Service;

import java.util.List;

@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);
    }
}

BookController.java

import com.demo.entity.Book;
import com.demo.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@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);
    }
}

配置分库分表策略application.properties:

# 数据源 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=123456

# 第二个数据库
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=123456

# 第三个数据库
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=123456

# 水平拆分的数据库(表) 配置分库 + 分表策略 行表达式分片策略
# 分库策略
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

配置Mapper扫描包:

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("com.demo.mapper")
@SpringBootApplication
public class SpringBootShardingsphereDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootShardingsphereDemoApplication.class, args);
    }

}

接口测试:
http://localhost:8080/book?id=2&name=Hadoop&count=8
http://localhost:8080/book

参考:
Spring Boot集成Sharding-jdbc + Mybatis-Plus实现分库分表

你可能感兴趣的:(#,SpringBoot)