有关分库分表前面写了三篇博客:html
一、分库分表(1) --- 理论java
二、分库分表(2) --- ShardingSphere(理论)node
三、分库分表(3) ---SpringBoot + ShardingSphere实现读写分离mysql
这篇博客经过ShardingSphere实现分表不分库
,并在文章最下方附上项目Github地址
。git
项目整体技术选型github
SpringBoot2.0.6 + shardingsphere4.0.0-RC1 + Maven3.5.4 + MySQL + lombok(插件)
场景
在实际开发中,若是表的数据过大,咱们可能须要把一张表拆分红多张表,这里就是经过ShardingSphere实现分表功能,但不分库。spring
这里有个member库,里面的tab_user
表由一张拆分红3张,分别是tab_user0
、tab_user1
、tab_user2
。sql
如图数据库
具体的建立表SQL也会放到GitHub项目里express
说明
完整的代码会放到GitHub上,这里只放一些核心代码。
server.port=8086 #指定mybatis信息 mybatis.config-location=classpath:mybatis-config.xml spring.shardingsphere.datasource.names=master # 数据源 主库 spring.shardingsphere.datasource.master.type=com.alibaba.druid.pool.DruidDataSource spring.shardingsphere.datasource.master.driver-class-name=com.mysql.jdbc.Driver spring.shardingsphere.datasource.master.url=jdbc:mysql://localhost:3306/member?characterEncoding=utf-8 spring.shardingsphere.datasource.master.username=root spring.shardingsphere.datasource.master.password=123456 #数据分表规则 #指定所需分的表 spring.shardingsphere.sharding.tables.tab_user.actual-data-nodes=master.tab_user$->{0..2} #指定主键 spring.shardingsphere.sharding.tables.tab_user.table-strategy.inline.sharding-column=id #分表规则为主键除以3取模 spring.shardingsphere.sharding.tables.tab_user.table-strategy.inline.algorithm-expression=tab_user$->{id % 3} #打印sql spring.shardingsphere.props.sql.show=true
Sharding-JDBC能够经过Java
,YAML
,Spring命名空间
和Spring Boot Starter
四种方式配置,开发者可根据场景选择适合的配置方式。具体能够看官网。
@RestController public class UserController { @Autowired private UserService userService; /** * 模拟插入数据 */ List<User> userList = Lists.newArrayList(); /** * 初始化插入数据 */ @PostConstruct private void getData() { userList.add(new User(1L,"小小", "女", 3)); userList.add(new User(2L,"爸爸", "男", 30)); userList.add(new User(3L,"妈妈", "女", 28)); userList.add(new User(4L,"爷爷", "男", 64)); userList.add(new User(5L,"奶奶", "女", 62)); } /** * @Description: 批量保存用户 */ @PostMapping("save-user") public Object saveUser() { return userService.insertForeach(userList); } /** * @Description: 获取用户列表 */ @GetMapping("list-user") public Object listUser() { return userService.list(); }
请求接口
localhost:8086/save-user
咱们能够从商品接口代码中能够看出,它会批量插入5条数据。咱们先看控制台输出SQL语句
咱们能够从SQL语句能够看出 tab_user1 和 tab_user2 表插入了两条数据
,而 tab_user0 表中插入一条数据
。
咱们再来看数据库
tab_user0
tab_user1
tab_user2
完成分表插入数据。
咱们来获取列表的SQL,这里对SQL作了order排序操做,具体ShardingSphere分表实现order操做的原理能够看上面一篇博客。
select * from tab_user order by id
请求接口结果
咱们能够看出虽然已经分表,但依然能够将多表数据聚合在一块儿并能够排序。
注意
ShardingSphere并不支持CASE WHEN
、HAVING
、UNION (ALL)
,有限支持子查询
。这个官网有详细说明。
Github地址
:https://github.com/yudiandemingzi/spring-boot-sharding-sphere
我相信,不管从此的道路多么坎坷,只要抓住今天,早晚会在奋斗中尝到人生的甘甜。抓住人生中的一分一秒,赛过虚度中的一月一年!(19)