Sharding-jdbc是开源的数据库操作中间件;定位为轻量级Java框架,在Java的JDBC层提供的额外服务。它使用客户端直连数据库,以jar包形式提供服务,无需额外部署和依赖,可理解为增强版的JDBC驱动,完全兼容JDBC和各种ORM框架。
Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。这是官方给的定义,关于mybatis-plus的更多介绍及特性,可以参考mybatis-plus官网。那么它是怎么增强的呢?其实就是它已经封装好了一些crud方法,我们不需要再写xml了,直接调用这些方法就行,就类似于JPA。还可以实现代码生成器,简单使用参见SpringBoot整合MyBatis-Plus。
源码地址
1.首先创建一个一般的Spring boot项目,目录结构如下:
2.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
3.配置
# 数据源 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行,可调整,当前用count
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 =
4.创建实体类:
@TableName("book")
public class Book {
private int id;
private int count;
private String name;
//getter,setter....喜欢lombok的同学可以用lombok
}
5.根据实体类创建数据库表:
创建三个库三张表
6.创建请求接口,目前只是创建两个,一个插一个查:
BookController .java
@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);
}
}
BookService.java
@Repository
public interface BookService extends IService<Book> {
List<Book> getBookList();
boolean save(Book book);
}
BookServiceImpl.java
@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
@Mapper
public interface BookMapper extends BaseMapper<Book> {
}
7.启动程序,测试验证:
程序启动后,使用postman发送post请求:http://localhost:8080/book?id=1&name=java1&count=6不断 更改id和count,检查落库是否成功。
2020-06-16 16:02:29.826 INFO 8740 --- [nio-8080-exec-6] ShardingSphere-SQL : Rule Type: sharding
2020-06-16 16:02:29.826 INFO 8740 --- [nio-8080-exec-6] ShardingSphere-SQL : Logic SQL: INSERT INTO book ( id,
count,
name ) VALUES ( ?,
?,
? )
2020-06-16 16:02:29.826 INFO 8740 --- [nio-8080-exec-6] ShardingSphere-SQL : SQLStatement: InsertStatement(super=DMLStatement(super=io.shardingsphere.core.parsing.parser.sql.dml.insert.InsertStatement@7d30408b), columns=[Column(name=id, tableName=book), Column(name=count, tableName=book), Column(name=name, tableName=book)], generatedKeyConditions=[], insertValues=InsertValues(insertValues=[InsertValue(type=VALUES, expression=( ?,
?,
? ), parametersCount=3)]), columnsListLastPosition=36, generateKeyColumnIndex=-1, insertValuesListLastPosition=58)
2020-06-16 16:02:29.826 INFO 8740 --- [nio-8080-exec-6] ShardingSphere-SQL : Actual SQL: db2 ::: INSERT INTO book_2 ( id,
count,
name ) VALUES ( ?,
?,
? ) ::: [[5, 5, java4]]
2020-06-16 16:02:40.152 INFO 8740 --- [nio-8080-exec-5] ShardingSphere-SQL : Rule Type: sharding
2020-06-16 16:02:40.152 INFO 8740 --- [nio-8080-exec-5] ShardingSphere-SQL : Logic SQL: INSERT INTO book ( id,
count,
name ) VALUES ( ?,
?,
? )