|
| 1 | +# spring-boot-demo-sharding-jdbc |
| 2 | + |
| 3 | +> 本 demo 主要演示了如何集成 `sharding-jdbc` 实现分库分表操作,ORM 层使用了`Mybatis-Plus`简化开发,童鞋们可以按照自己的喜好替换为 JPA、通用Mapper、JdbcTemplate甚至原生的JDBC都可以。 |
| 4 | +> |
| 5 | +> PS: |
| 6 | +> |
| 7 | +> 1. 目前当当官方提供的starter存在bug,版本号:`3.1.0`,因此本demo采用手动配置。 |
| 8 | +> 2. 文档真的很垃圾 :joy: |
| 9 | +
|
| 10 | +## 1. 运行方式 |
| 11 | + |
| 12 | +1. 在数据库创建2个数据库,分别为:`spring-boot-demo`、`spring-boot-demo-2` |
| 13 | +2. 去数据库执行 `sql/schema.sql` ,创建 `6` 张分片表 |
| 14 | +3. 找到 `DataSourceShardingConfig` 配置类,修改 `数据源` 的相关配置,位于 `dataSourceMap()` 这个方法 |
| 15 | +4. 找到测试类 `SpringBootDemoShardingJdbcApplicationTests` 进行测试 |
| 16 | + |
| 17 | +## 2. 关键代码 |
| 18 | + |
| 19 | +### 2.1. `pom.xml` |
| 20 | + |
| 21 | +```xml |
| 22 | +<?xml version="1.0" encoding="UTF-8"?> |
| 23 | +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
| 24 | + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> |
| 25 | + <modelVersion>4.0.0</modelVersion> |
| 26 | + |
| 27 | + <artifactId>spring-boot-demo-sharding-jdbc</artifactId> |
| 28 | + <version>1.0.0-SNAPSHOT</version> |
| 29 | + <packaging>jar</packaging> |
| 30 | + |
| 31 | + <name>spring-boot-demo-sharding-jdbc</name> |
| 32 | + <description>Demo project for Spring Boot</description> |
| 33 | + |
| 34 | + <parent> |
| 35 | + <groupId>com.xkcoding</groupId> |
| 36 | + <artifactId>spring-boot-demo</artifactId> |
| 37 | + <version>1.0.0-SNAPSHOT</version> |
| 38 | + </parent> |
| 39 | + |
| 40 | + <properties> |
| 41 | + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> |
| 42 | + <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> |
| 43 | + <java.version>1.8</java.version> |
| 44 | + </properties> |
| 45 | + |
| 46 | + <dependencies> |
| 47 | + <dependency> |
| 48 | + <groupId>org.springframework.boot</groupId> |
| 49 | + <artifactId>spring-boot-starter</artifactId> |
| 50 | + </dependency> |
| 51 | + |
| 52 | + <dependency> |
| 53 | + <groupId>org.springframework.boot</groupId> |
| 54 | + <artifactId>spring-boot-starter-test</artifactId> |
| 55 | + <scope>test</scope> |
| 56 | + </dependency> |
| 57 | + |
| 58 | + <dependency> |
| 59 | + <groupId>com.baomidou</groupId> |
| 60 | + <artifactId>mybatis-plus-boot-starter</artifactId> |
| 61 | + <version>3.1.0</version> |
| 62 | + </dependency> |
| 63 | + |
| 64 | + <dependency> |
| 65 | + <groupId>mysql</groupId> |
| 66 | + <artifactId>mysql-connector-java</artifactId> |
| 67 | + </dependency> |
| 68 | + |
| 69 | + <dependency> |
| 70 | + <groupId>io.shardingsphere</groupId> |
| 71 | + <artifactId>sharding-jdbc-core</artifactId> |
| 72 | + <version>3.1.0</version> |
| 73 | + </dependency> |
| 74 | + |
| 75 | + <dependency> |
| 76 | + <groupId>cn.hutool</groupId> |
| 77 | + <artifactId>hutool-all</artifactId> |
| 78 | + </dependency> |
| 79 | + |
| 80 | + <dependency> |
| 81 | + <groupId>org.projectlombok</groupId> |
| 82 | + <artifactId>lombok</artifactId> |
| 83 | + <optional>true</optional> |
| 84 | + </dependency> |
| 85 | + </dependencies> |
| 86 | + |
| 87 | + <build> |
| 88 | + <finalName>spring-boot-demo-sharding-jdbc</finalName> |
| 89 | + <plugins> |
| 90 | + <plugin> |
| 91 | + <groupId>org.springframework.boot</groupId> |
| 92 | + <artifactId>spring-boot-maven-plugin</artifactId> |
| 93 | + </plugin> |
| 94 | + </plugins> |
| 95 | + </build> |
| 96 | + |
| 97 | +</project> |
| 98 | +``` |
| 99 | + |
| 100 | +### 2.2. `DataSourceShardingConfig.java` |
| 101 | + |
| 102 | +```java |
| 103 | +/** |
| 104 | + * <p> |
| 105 | + * sharding-jdbc 的数据源配置 |
| 106 | + * </p> |
| 107 | + * |
| 108 | + * @package: com.xkcoding.sharding.jdbc.config |
| 109 | + * @description: sharding-jdbc 的数据源配置 |
| 110 | + * @author: yangkai.shen |
| 111 | + * @date: Created in 2019-03-26 16:47 |
| 112 | + * @copyright: Copyright (c) 2019 |
| 113 | + * @version: V1.0 |
| 114 | + * @modified: yangkai.shen |
| 115 | + */ |
| 116 | +@Configuration |
| 117 | +public class DataSourceShardingConfig { |
| 118 | + /** |
| 119 | + * 需要手动配置事务管理器 |
| 120 | + */ |
| 121 | + @Bean |
| 122 | + public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) { |
| 123 | + return new DataSourceTransactionManager(dataSource); |
| 124 | + } |
| 125 | + |
| 126 | + @Bean(name = "dataSource") |
| 127 | + @Primary |
| 128 | + public DataSource dataSource() throws SQLException { |
| 129 | + ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); |
| 130 | + // 设置分库策略 |
| 131 | + shardingRuleConfig.setDefaultDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("user_id", "ds${user_id % 2}")); |
| 132 | + // 设置规则适配的表 |
| 133 | + shardingRuleConfig.getBindingTableGroups().add("t_order"); |
| 134 | + // 设置分表策略 |
| 135 | + shardingRuleConfig.getTableRuleConfigs().add(orderTableRule()); |
| 136 | + shardingRuleConfig.setDefaultDataSourceName("ds0"); |
| 137 | + shardingRuleConfig.setDefaultTableShardingStrategyConfig(new NoneShardingStrategyConfiguration()); |
| 138 | + |
| 139 | + Properties properties = new Properties(); |
| 140 | + properties.setProperty("sql.show", "true"); |
| 141 | + |
| 142 | + return ShardingDataSourceFactory.createDataSource(dataSourceMap(), shardingRuleConfig, new ConcurrentHashMap<>(16), properties); |
| 143 | + } |
| 144 | + |
| 145 | + private TableRuleConfiguration orderTableRule() { |
| 146 | + TableRuleConfiguration tableRule = new TableRuleConfiguration(); |
| 147 | + // 设置逻辑表名 |
| 148 | + tableRule.setLogicTable("t_order"); |
| 149 | + // ds${0..1}.t_order_${0..2} 也可以写成 ds$->{0..1}.t_order_$->{0..1} |
| 150 | + tableRule.setActualDataNodes("ds${0..1}.t_order_${0..2}"); |
| 151 | + tableRule.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("order_id", "t_order_$->{order_id % 3}")); |
| 152 | + tableRule.setKeyGenerator(new DefaultKeyGenerator()); |
| 153 | + tableRule.setKeyGeneratorColumnName("order_id"); |
| 154 | + return tableRule; |
| 155 | + } |
| 156 | + |
| 157 | + private Map<String, DataSource> dataSourceMap() { |
| 158 | + Map<String, DataSource> dataSourceMap = new HashMap<>(16); |
| 159 | + |
| 160 | + // 配置第一个数据源 |
| 161 | + HikariDataSource ds0 = new HikariDataSource(); |
| 162 | + ds0.setDriverClassName("com.mysql.cj.jdbc.Driver"); |
| 163 | + ds0.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/spring-boot-demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8"); |
| 164 | + ds0.setUsername("root"); |
| 165 | + ds0.setPassword("root"); |
| 166 | + |
| 167 | + // 配置第二个数据源 |
| 168 | + HikariDataSource ds1 = new HikariDataSource(); |
| 169 | + ds1.setDriverClassName("com.mysql.cj.jdbc.Driver"); |
| 170 | + ds1.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/spring-boot-demo-2?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8"); |
| 171 | + ds1.setUsername("root"); |
| 172 | + ds1.setPassword("root"); |
| 173 | + |
| 174 | + dataSourceMap.put("ds0", ds0); |
| 175 | + dataSourceMap.put("ds1", ds1); |
| 176 | + return dataSourceMap; |
| 177 | + } |
| 178 | + |
| 179 | +} |
| 180 | +``` |
| 181 | + |
| 182 | +### 2.3. `SpringBootDemoShardingJdbcApplicationTests.java` |
| 183 | + |
| 184 | +```java |
| 185 | +/** |
| 186 | + * <p> |
| 187 | + * 测试sharding-jdbc分库分表 |
| 188 | + * </p> |
| 189 | + * |
| 190 | + * @package: com.xkcoding.sharding.jdbc |
| 191 | + * @description: 测试sharding-jdbc分库分表 |
| 192 | + * @author: yangkai.shen |
| 193 | + * @date: Created in 2019-03-26 13:44 |
| 194 | + * @copyright: Copyright (c) 2019 |
| 195 | + * @version: V1.0 |
| 196 | + * @modified: yangkai.shen |
| 197 | + */ |
| 198 | +@Slf4j |
| 199 | +@RunWith(SpringRunner.class) |
| 200 | +@SpringBootTest |
| 201 | +public class SpringBootDemoShardingJdbcApplicationTests { |
| 202 | + @Autowired |
| 203 | + private OrderMapper orderMapper; |
| 204 | + |
| 205 | + /** |
| 206 | + * 测试新增 |
| 207 | + */ |
| 208 | + @Test |
| 209 | + public void testInsert() { |
| 210 | + for (long i = 1; i < 10; i++) { |
| 211 | + for (long j = 1; j < 20; j++) { |
| 212 | + Order order = Order.builder().userId(i).orderId(j).remark(RandomUtil.randomString(20)).build(); |
| 213 | + orderMapper.insert(order); |
| 214 | + } |
| 215 | + } |
| 216 | + } |
| 217 | + |
| 218 | + /** |
| 219 | + * 测试更新 |
| 220 | + */ |
| 221 | + @Test |
| 222 | + public void testUpdate() { |
| 223 | + Order update = new Order(); |
| 224 | + update.setRemark("修改备注信息"); |
| 225 | + orderMapper.update(update, Wrappers.<Order>update().lambda().eq(Order::getOrderId, 2).eq(Order::getUserId, 2)); |
| 226 | + } |
| 227 | + |
| 228 | + /** |
| 229 | + * 测试删除 |
| 230 | + */ |
| 231 | + @Test |
| 232 | + public void testDelete() { |
| 233 | + orderMapper.delete(new QueryWrapper<>()); |
| 234 | + } |
| 235 | + |
| 236 | + /** |
| 237 | + * 测试查询 |
| 238 | + */ |
| 239 | + @Test |
| 240 | + public void testSelect() { |
| 241 | + List<Order> orders = orderMapper.selectList(Wrappers.<Order>query().lambda().in(Order::getOrderId, 1, 2)); |
| 242 | + log.info("【orders】= {}", JSONUtil.toJsonStr(orders)); |
| 243 | + } |
| 244 | + |
| 245 | +} |
| 246 | +``` |
| 247 | + |
| 248 | +## 3. 参考 |
| 249 | + |
| 250 | +1. `ShardingSphere` 官网:https://shardingsphere.apache.org/index_zh.html (虽然文档确实垃圾,但是还是得参考啊~) |
| 251 | +2. `Mybatis-Plus` 语法参考官网:https://mybatis.plus/ |
0 commit comments