ShardingSphere定位為輕量級 Java 框架,在 Java 的 JDBC 層提供的額外服務。 它使用客戶端直連數據庫,以 jar 包形式提供服務,無需額外部署和依賴,可理解為增強版的 JDBC 驅動,完全兼容 JDBC 和各種 ORM 框架。
代碼實現:
以用戶表為例, 我們需要將它分成2個庫,每個庫三張表,根據id字段取模確定最終數據的位置
ds0:
user_0
user_1
user_2
ds1:
user_0
user_1
user_2
ds0,ds1兩個數據庫的三張表的邏輯表都為user表,可以使用以下腳本建表:
CREATE TABLE `user_0` (
`id` bigint(11) NOT NULL,
`name` varchar(20) COLLATE utf8_bin DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
修改pom.xml文件
mybatis-plus配置信息類:
用戶實體類:
用戶dao接口類:
springboot啟動類:
測試類userController:
package com.mscloudmesh.sharding.springbootshardingsphere.controller;
import com.mscloudmesh.sharding.springbootshardingsphere.model.User;
import com.mscloudmesh.sharding.springbootshardingsphere.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/add")
public User add() {
User user = new User();
user.setName("test");
user.setAge(30);
userService.save(user);
return user;
}
}
請求 http://localhost:8761/add
控制台輸出:

