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

一、Sharding-JDBC简介:

    Sharding-JDBC又称ShardingSphere,一个开放源代码生态系统,由一组分布式数据库中间件解决方案组成,其中又包括JDBC,代理和Sidecar(计划)。它们都提供数据分片,分布式事务和数据库编排功能,适用于Java同构,异构语言和云原生等各种情况。

二、创建项目如下:

    使用STS创建Spring Boot项目,使用MVC三层结构开发代码:

    1)配置POM添加以下依赖

        

       

            mysql

            mysql-connector-java

            runtime

       

       

       

            com.baomidou

            mybatis-plus-boot-starter

            3.1.1

       

       

       

       

            io.shardingsphere

            sharding-jdbc-spring-boot-starter

            3.1.0

       

       

       

            io.shardingsphere

            sharding-jdbc-spring-namespace

            3.1.0

       

       

       

       

            org.projectlombok

            lombok

       

    2)创建实体类

        @Data

        @EqualsAndHashCode(callSuper = true)

        @Accessors(chain = true)

        @TableName("book")

        public class Book extends Model {

            private int id;

            private String name;

            private int count;
        }

    3)创建service

        public interface BookService {

            List getBookList();

            boolean save(Book book);

        }

    4)创建serviceImpl

        @Service

        public class BookServiceImpl extends ServiceImplimplements BookService{

            @Override

            public List getBookList() {

                return baseMapper.selectList(Wrappers.lambdaQuery());

            }

            @Override

            public boolean save(Book book) {

                return super.save(book);

            }

    }

    5)创建controller,并实现以下两个方法

        @RestController

        public class BookController {

        @Autowired

        BookService bookService;

        @RequestMapping(value = "/book", method = RequestMethod.GET)

        public List getItems(){

                return bookService.getBookList();

            }

        @RequestMapping(value = "/book",method = RequestMethod.POST)

        public Boolean saveItem(Book book){

            return bookService.save(book);

            }

        }

    6)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=root

        # 第二个数据库

        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=root

        # 第三个数据库

        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=root

        # 水平拆分的数据库(表) 配置分库 + 分表策略 行表达式分片策略

        # 分库策略

        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..1}

        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 % 2}

        # 主键 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=

    7)sql建表语句如下

        #创建数据库表数据

        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;

三、启动项目用postman访问如下地址:

使用post请求插入参数,点击send按钮

    

返回插入成功状态为true


使用get请求获取插入数据,如上图所示

你可能感兴趣的:(Spring Boot 集成 Sharding-JDBC + Mybatis-Plus 实现分库分表)