一、前言
一般来说,随着业务的发展数据库的数据量会越来越多,当单表数据超过上千万时执行一些查询sql语句就会遇到性能问题。一开始可以用主从复制读写分离来减轻db压力,但是后面还是要用分库分表把数据进行水平拆分和垂直拆分。
实现分库分表目前我知道的方式有两种,第一种是使用mycat中间件实现,第二种是使用sharding-jdbc实现。相比较而言,sharding-jdbc引入一个jar包即可使用更轻量级一些,它们之间的优缺点这里也不做比较,有兴趣的可以自己搜索相关资料。
不清楚分库分表原理的可以参考这篇博客,数据库之分库分表-垂直?水平?
二、使用当当网的sharding-jdbc分库分表
2.1新建SpringBoot项目
新建项目sharding-jdbc-first,并在pom文件添加如下内容:
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>1.5.16.RELEASE</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
-
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <java.version>1.8</java.version>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-jpa</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
-
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.dangdang</groupId>
- <artifactId>sharding-jdbc-core</artifactId>
- <version>1.4.2</version>
- </dependency>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.0.12</version>
- </dependency>
-
- <dependency>
- <groupId>com.dangdang</groupId>
- <artifactId>sharding-jdbc-self-id-generator</artifactId>
- <version>1.4.2</version>
- </dependency>
-
-
- </dependencies>
目前好像不支持SpringBoot2.0以上的版本。
2.2编写实体类及建库建表
目标:
db0
├── t_order_0 user_id为偶数 order_id为偶数
├── t_order_1 user_id为偶数 order_id为奇数
db1
├── t_order_0 user_id为奇数 order_id为偶数
├── t_order_1 user_id为奇数 order_id为奇数
- 创建两个数据库 ds_0 和 ds_1,编码类型UTF-8。
- 每个库分表创建两个表t_order_0和t_order_1,sql语句如下:
DROP TABLE IF EXISTS t_order_0;
CREATE TABLE t_order_0 (
order_id bigint(20) NOT NULL,
user_id bigint(20) NOT NULL,
PRIMARY KEY (order_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
- 新建类Order,代码如下
- package cn.sp.bean;
-
- import javax.persistence.Entity;
- import javax.persistence.Id;
- import javax.persistence.Table;
-
- /**
- * Created by 2YSP on 2018/9/23.
- */
- @Entity
- @Table(name="t_order")
- public class Order {
- @Id
- private Long orderId;
-
- private Long userId;
-
- public Long getOrderId() {
- return orderId;
- }
-
- public void setOrderId(Long orderId) {
- this.orderId = orderId;
- }
-
- public Long getUserId() {
- return userId;
- }
-
- public void setUserId(Long userId) {
- this.userId = userId;
- }
- }
-
这里需要注意 @Id注解不要导错包,之前我就遇到过这个问题。
4.配置文件application.yml
- server:
- port: 8000
- spring:
- jpa:
- database: mysql
- show-sql: true
- hibernate:
- ## 自己建表
- ddl-auto: none
- application:
- name: sharding-jdbc-first
这里要注意的是spring-data-jpa默认会自己建表,这里我们要手动建立,所以需要将ddl-auto属性设置为none。
2.3自定义分库分表算法
1.分库算法类需要实现SingleKeyDatabaseShardingAlgorithm<T>接口,这是一个泛型接口,T代表分库依据的字段的类型,比如我们根据userId%2来分库,userId是Long型的,这里的T就是Long。
- public class ModuloDatabaseShardingAlgorithm implements SingleKeyDatabaseShardingAlgorithm<Long> {
- @Override
- public String doEqualSharding(Collection<String> availableDatabaseNames, ShardingValue<Long> shardingValue) {
- for(String databaseName : availableDatabaseNames){
- if (databaseName.endsWith(shardingValue.getValue() % 2 + "")){
-
- return databaseName;
- }
- }
- throw new IllegalArgumentException();
- }
-
- @Override
- public Collection<String> doInSharding(Collection<String> availableDatabaseNames, ShardingValue<Long> shardingValue) {
- Collection<String> result = new LinkedHashSet<>(availableDatabaseNames.size());
- for(Long value : shardingValue.getValues()){
- for(String name : availableDatabaseNames){
- if (name.endsWith(value%2 + "")){
- result.add(name);
- }
- }
- }
- return result;
- }
-
- @Override
- public Collection<String> doBetweenSharding(Collection<String> availableDatabaseNames, ShardingValue<Long> shardingValue) {
- Collection<String> result = new LinkedHashSet<>(availableDatabaseNames.size());
- Range<Long> range = shardingValue.getValueRange();
- for(Long i = range.lowerEndpoint() ; i < range.upperEndpoint();i++){
- for(String each : availableDatabaseNames){
- if (each.endsWith( i % 2+"")){
- result.add(each);
- }
- }
- }
-
- return result;
- }
- }
-
2.分表算法类需要实现SingleKeyTableShardingAlgorithm<T>接口。
- /**
- * 表分片算法
- * Created by 2YSP on 2018/9/23.
- */
- public class ModuloTableShardingAlgorithm implements SingleKeyTableShardingAlgorithm<Long> {
-
- /**
- * select * from t_order from t_order where order_id = 11
- * └── SELECT * FROM t_order_1 WHERE order_id = 11
- * select * from t_order from t_order where order_id = 44
- * └── SELECT * FROM t_order_0 WHERE order_id = 44
- */
- @Override
- public String doEqualSharding(Collection<String> tableNames, ShardingValue<Long> shardingValue) {
- for (String tableName : tableNames) {
- if (tableName.endsWith(shardingValue.getValue() % 2 + "")) {
- return tableName;
- }
- }
-
- throw new IllegalArgumentException();
- }
-
- /**
- * select * from t_order from t_order where order_id in (11,44)
- * ├── SELECT * FROM t_order_0 WHERE order_id IN (11,44)
- * └── SELECT * FROM t_order_1 WHERE order_id IN (11,44)
- * select * from t_order from t_order where order_id in (11,13,15)
- * └── SELECT * FROM t_order_1 WHERE order_id IN (11,13,15)
- * select * from t_order from t_order where order_id in (22,24,26)
- * └──SELECT * FROM t_order_0 WHERE order_id IN (22,24,26)
- */
- @Override
- public Collection<String> doInSharding(Collection<String> tableNames, ShardingValue<Long> shardingValue) {
- Collection<String> result = new LinkedHashSet<>(tableNames.size());
- for (Long value : shardingValue.getValues()) {
- for (String table : tableNames) {
- if (table.endsWith(value % 2 + "")) {
- result.add(table);
- }
- }
- }
- return result;
- }
-
- /**
- * select * from t_order from t_order where order_id between 10 and 20
- * ├── SELECT * FROM t_order_0 WHERE order_id BETWEEN 10 AND 20
- * └── SELECT * FROM t_order_1 WHERE order_id BETWEEN 10 AND 20
- */
- @Override
- public Collection<String> doBetweenSharding(Collection<String> tableNames, ShardingValue<Long> shardingValue) {
- Collection<String> result = new LinkedHashSet<>(tableNames.size());
- Range<Long> range = shardingValue.getValueRange();
- for (Long i = range.lowerEndpoint(); i < range.upperEndpoint(); i++) {
- for (String each : tableNames) {
- if (each.endsWith(i % 2 + "")) {
- result.add(each);
- }
- }
- }
-
- return result;
- }
- }
2.4配置数据源
数据源配置类DataSourceConfig
- @Configuration
- public class DataSourceConfig {
- @Bean
- public IdGenerator getIdGenerator(){
- return new CommonSelfIdGenerator();
- }
-
- @Bean
- public DataSource getDataSource() {
- return buildDataSource();
- }
-
-
- private DataSource buildDataSource() {
- //1.设置分库映射
- Map<String, DataSource> dataSourceMap = new HashMap<>(2);
- dataSourceMap.put("ds_0", createDataSource("ds_0"));
- dataSourceMap.put("ds_1", createDataSource("ds_1"));
- //设置默认db为ds_0,也就是为那些没有配置分库分表策略的指定的默认库
- //如果只有一个库,也就是不需要分库的话,map里只放一个映射就行了,只有一个库时不需要指定默认库,
- // 但2个及以上时必须指定默认库,否则那些没有配置策略的表将无法操作数据
- DataSourceRule rule = new DataSourceRule(dataSourceMap, "ds_0");
-
- //2.设置分表映射,将t_order_0和t_order_1两个实际的表映射到t_order逻辑表
- TableRule orderTableRule = TableRule.builder("t_order")
- .actualTables(Arrays.asList("t_order_0", "t_order_1"))
- .dataSourceRule(rule)
- .build();
- //3.具体的分库分表策略
- ShardingRule shardingRule = ShardingRule.builder()
- .dataSourceRule(rule)
- .tableRules(Arrays.asList(orderTableRule))
- .databaseShardingStrategy(new DatabaseShardingStrategy("user_id", new ModuloDatabaseShardingAlgorithm()))
- .tableShardingStrategy(new TableShardingStrategy("order_id", new ModuloTableShardingAlgorithm()))
- .build();
-
- DataSource dataSource = ShardingDataSourceFactory.createDataSource(shardingRule);
- return dataSource;
- }
-
- private static DataSource createDataSource(String dataSourceName) {
- //使用druid连接数据库
- DruidDataSource druidDataSource = new DruidDataSource();
- druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
- druidDataSource.setUrl(String.format("jdbc:mysql://localhost:3306/%s?characterEncoding=utf-8", dataSourceName));
- druidDataSource.setUsername("root");
- druidDataSource.setPassword("1234");
- return druidDataSource;
- }
- }
这里的一些配置信息url,username,password等可以优化下,从配置文件读取。
2.5测试
1.新建OrderRepository
- public interface OrderRepository extends CrudRepository<Order,Long> {
-
- }
2.controller层
- /**
- * Created by 2YSP on 2018/9/23.
- */
- @RestController
- @RequestMapping("/order")
- public class OrderController {
-
- @Autowired
- private OrderRepository repository;
-
- @Autowired
- private IdGenerator idGenerator;
-
- @RequestMapping("/add")
- public String add(){
- for(int i=0;i<10;i++){
- Order order = new Order();
- order.setOrderId((long) i);
- order.setUserId((long) i);
- repository.save(order);
- }
- // Order order = new Order();
- // order.setUserId(1L);
- // order.setOrderId(idGenerator.generateId().longValue());
- // repository.save(order);
- return "success";
- }
-
- @RequestMapping("/query")
- public List<Order> queryAll(){
- List<Order> orders = (List<Order>) repository.findAll();
- return orders;
- }
- }
-
3.访问http://localhost:8080/order/add,即可在数据库ds_0,ds_1发现多了一些数据。
访问http://localhost:8080/order/query可以查询刚刚添加的订单数据。
完整代码地址:https://github.com/2YSP/sharding-jdbc-first
三、使用sharding-jdbc-spring-boot-starter分库分表
暂时省略,可以访问github地址了解更多。
四、总结
在分库分表的时候要根据实际情况来决定根据哪个字段来分(不一定都是主键),需要分几个库几张表。
分库分表后遇到的问题:
1.不能像以前一样使用数据库自增的主键了,会出现主键重复的问题(可以使用分布式主键来代替)。
2.不支持一些关键字。
3.在做一些统计查询的时候也更加困难,那时候可能需要引入搜索引擎ES了。
4.之前以为sharding-jdbc不支持分页操作,那天测试了下竟然可以。
原文地址:https://www.cnblogs.com/2YSP/p/9746981.html