有關分庫分表前面寫了三篇博客: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
<br>
說明
完整的代碼會放到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(); }
<br>
請求接口
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
請求接口結果
<img src="https://img2018.cnblogs.com/blog/1090617/201910/1090617-20191011191043297-1315264145.jpg" style="border: 1px dashed rgb(204, 200, 200);" width="700" height="620">
咱們能夠看出雖然已經分表,但依然能夠將多表數據聚合在一塊兒並能夠排序。
注意
ShardingSphere並不支持CASE WHEN
、HAVING
、UNION (ALL)
,有限支持子查詢
。這個官網有詳細說明。
Github地址
:https://github.com/yudiandemingzi/spring-boot-sharding-sphere
<br>
<br> <br>
我相信,不管從此的道路多麼坎坷,只要抓住今天,早晚會在奮鬥中嚐到人生的甘甜。抓住人生中的一分一秒,賽過虛度中的一月一年!(19)
<br>
原文出處:https://www.cnblogs.com/qdhxhz/p/11651163.html