这两天抽空搞了一下Sharding jdbc,鉴于现在做的项目中也用到了这块(不是我搞的),作为一名对技术痴迷的渣男,怎么可能无视它的存在,必须自己来搞一搞哈。
搞起~
项目搭建
1、新建一个spring boot工程,添加依赖
<dependencies>
<!--核心服务-->
<dependency>
<groupId>top.qrainly</groupId>
<artifactId>bj_core</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!--sharding-jdbc-->
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>3.1.0.M1</version>
</dependency>
<!--jmockdata-->
<dependency>
<groupId>com.github.jsonzou</groupId>
<artifactId>jmockdata</artifactId>
<version>4.1.2</version>
</dependency>
</dependencies>
这里友情推荐一下,依赖里用到了朋友开源的一个工具插件JMockData,此乃开发测试之利器,强烈推荐!!!
2、在master库执行sql脚本,创建用户表
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`username` varchar(12) NOT NULL,
`password` varchar(30) NOT NULL,
PRIMARY KEY (`id`),
KEY `idx-username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `user_0`;
CREATE TABLE `user_0` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`username` varchar(12) NOT NULL,
`password` varchar(30) NOT NULL,
PRIMARY KEY (`id`),
KEY `idx-username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `user_1`;
CREATE TABLE `user_1` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`username` varchar(12) NOT NULL,
`password` varchar(30) NOT NULL,
PRIMARY KEY (`id`),
KEY `idx-username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `user_2`;
CREATE TABLE `user_2` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`username` varchar(1