文章只讨论实现,具体原理可以参考官方网站

引入maven依赖

1
2
3
4
5
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-core</artifactId>
<version>4.0.0-RC1</version>
</dependency>

创建数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
-- --------------------------------------------------------
-- 主机: 127.0.0.1
-- 服务器版本: 8.0.18 - MySQL Community Server - GPL
-- 服务器OS: Win64
-- HeidiSQL 版本: 10.2.0.5599
-- --------------------------------------------------------

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;


-- Dumping database structure for ds0
CREATE DATABASE IF NOT EXISTS `ds0` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci */ /*!80016 DEFAULT ENCRYPTION='N' */;
USE `ds0`;

-- Dumping structure for table ds0.t_order0
CREATE TABLE IF NOT EXISTS `t_order0` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) DEFAULT NULL COMMENT '用户ID',
`descr` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '描述',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=424525194623713281 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='订单表';

-- Dumping data for table ds0.t_order0: ~4 rows (大约)
DELETE FROM `t_order0`;
/*!40000 ALTER TABLE `t_order0` DISABLE KEYS */;
/*!40000 ALTER TABLE `t_order0` ENABLE KEYS */;

-- Dumping structure for table ds0.t_order1
CREATE TABLE IF NOT EXISTS `t_order1` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) DEFAULT NULL COMMENT '用户ID',
`descr` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '描述',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=424525194640490498 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='订单表';

-- Dumping data for table ds0.t_order1: ~8 rows (大约)
DELETE FROM `t_order1`;
/*!40000 ALTER TABLE `t_order1` DISABLE KEYS */;
/*!40000 ALTER TABLE `t_order1` ENABLE KEYS */;


-- Dumping database structure for ds1
CREATE DATABASE IF NOT EXISTS `ds1` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci */ /*!80016 DEFAULT ENCRYPTION='N' */;
USE `ds1`;

-- Dumping structure for table ds1.t_order0
CREATE TABLE IF NOT EXISTS `t_order0` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) DEFAULT NULL COMMENT '用户ID',
`descr` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '描述',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='订单表';

-- Dumping data for table ds1.t_order0: ~0 rows (大约)
DELETE FROM `t_order0`;
/*!40000 ALTER TABLE `t_order0` DISABLE KEYS */;
/*!40000 ALTER TABLE `t_order0` ENABLE KEYS */;

-- Dumping structure for table ds1.t_order1
CREATE TABLE IF NOT EXISTS `t_order1` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) DEFAULT NULL COMMENT '用户ID',
`descr` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '描述',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=424521077465546754 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='订单表';

-- Dumping data for table ds1.t_order1: ~3 rows (大约)
DELETE FROM `t_order1`;
/*!40000 ALTER TABLE `t_order1` DISABLE KEYS */;
/*!40000 ALTER TABLE `t_order1` ENABLE KEYS */;

/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;

配置yml文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
spring:
datasource0:
jdbc-url: jdbc:mysql://localhost/ds0?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&allowPublicKeyRetrieval=true
username: root
password: dreamlyn
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
pool-name: HikariCP
auto-commit: false

datasource1:
jdbc-url: jdbc:mysql://localhost/ds1?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&allowPublicKeyRetrieval=true
username: root
password: dreamlyn
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
pool-name: HikariCP
auto-commit: false
mybatis-plus:
tenant-enable: true
mapper-locations: classpath:/mapper/*Mapper.xml
global-config:
banner: false
db-config:
id-type: auto
field-strategy: NOT_EMPTY

配置数据源

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* ds0 data source.
*/
@Bean("ds0DataSource")
@ConfigurationProperties(prefix = "spring.datasource0")
DataSource ds0DataSource() {
return DataSourceBuilder.create().build();
}

/**
* ds1 (read only) data source.
*/
@Bean("ds1DataSource")
@ConfigurationProperties(prefix = "spring.datasource1")
DataSource ds1DataSource() {
return DataSourceBuilder.create().build();
}

@Bean
@Primary
DataSource primaryDataSource(
@Autowired @Qualifier("ds0DataSource") DataSource ds0DataSource,
@Autowired @Qualifier("ds1DataSource") DataSource ds1DataSource
) throws SQLException {
Map<String, DataSource> dataSourceMap = new HashMap<>();
dataSourceMap.put("ds0", ds0DataSource);
dataSourceMap.put("ds1", ds1DataSource);


// 配置Order表规则
TableRuleConfiguration orderTableRuleConfig =
new TableRuleConfiguration("t_order", "ds${0..1}.t_order${0..1}");
// 配置分库 + 分表策略
orderTableRuleConfig.setDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("user_id", "ds${user_id % 2}"));
orderTableRuleConfig.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("id", "t_order${id % 2}"));
//key生成算法
orderTableRuleConfig.setKeyGeneratorConfig(new KeyGeneratorConfiguration("SNOWFLAKE", "id"));
// 配置分片规则
ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
shardingRuleConfig.getTableRuleConfigs().add(orderTableRuleConfig);
// 省略配置order_item表规则...
// ...
// 获取数据源对象
DataSource dataSource = ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfig, new Properties());
return dataSource;
}

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Autowired
private TOrderMapper TOrderMapper;

@Override
public void run(ApplicationArguments args) throws Exception {
TOrder tOrder = new TOrder();
tOrder.setUserId(0L);
tOrder.setDescr("测试");
TOrderMapper.insert(tOrder);
TOrderMapper.insert(tOrder);
TOrderMapper.insert(tOrder);
TOrderMapper.insert(tOrder);
TOrderMapper.insert(tOrder);

//设置数据源
List<TOrder> TOrders = TOrderMapper.selectList(null);
log.info("orders:{}", TOrders);


}

源码

源码请到此处下载