Druid 分表分库 使用实例
时间: 2023-08-15 11:07:55 浏览: 188
分库分表案例.rar
下面给出一个使用Druid连接池实现分表分库的示例:
1. 添加Druid连接池依赖,例如在Maven项目中添加以下依赖:
```xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.3</version>
</dependency>
```
2. 配置Druid连接池,例如在Spring Boot项目中可以在application.properties文件中添加以下配置:
```properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.testWhileIdle=true
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=25200000
spring.datasource.filters=stat,wall,log4j
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
```
其中,spring.datasource.url中的testdb是数据库名,可以根据实际情况修改为自己的数据库名。
3. 实现分表分库功能,例如可以在代码中使用Sharding-JDBC来实现分表分库功能,具体实现方式可以参考以下示例:
```java
@Configuration
public class DataSourceConfiguration {
@Bean
public DataSource dataSource() throws SQLException {
Map<String, DataSource> dataSourceMap = new HashMap<>();
dataSourceMap.put("ds0", createDataSource("ds0"));
dataSourceMap.put("ds1", createDataSource("ds1"));
ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
shardingRuleConfig.getTableRuleConfigs().add(getOrderTableRuleConfiguration());
shardingRuleConfig.getBindingTableGroups().add("t_order");
return ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfig, new Properties());
}
private TableRuleConfiguration getOrderTableRuleConfiguration() {
TableRuleConfiguration result = new TableRuleConfiguration("t_order", "ds${0..1}.t_order_${0..1}");
result.setDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("user_id", "ds${user_id % 2}"));
result.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("order_id", "t_order_${order_id % 2}"));
return result;
}
private DataSource createDataSource(final String dataSourceName) throws SQLException {
DruidDataSource result = new DruidDataSource();
result.setDriverClassName("com.mysql.jdbc.Driver");
result.setUrl(String.format("jdbc:mysql://localhost:3306/%s?useUnicode=true&characterEncoding=utf8&useSSL=false", dataSourceName));
result.setUsername("root");
result.setPassword("root");
return result;
}
}
```
以上示例中,创建了两个数据源ds0和ds1,分别对应了两个数据库,使用Sharding-JDBC实现了分表分库功能,其中按照user_id对数据进行分库,按照order_id对表进行分表。
阅读全文