java中sharding配置好后加入连接池怎么做
时间: 2024-05-10 11:20:35 浏览: 237
1. 首先需要引入ShardingSphere的数据源代理模块和连接池模块的依赖:
```
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-core</artifactId>
<version>${sharding-sphere.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-core-spring-boot-starter</artifactId>
<version>${sharding-sphere.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-core-elasticjob-lite-spring-boot-starter</artifactId>
<version>${sharding-sphere.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-core-orchestration-spring-boot-starter</artifactId>
<version>${sharding-sphere.version}</version>
</dependency>
```
2. 在application.yml文件中配置数据源及连接池:
```
spring:
datasource:
# 主库配置
master:
url: jdbc:mysql://localhost:3306/master_db?useSSL=false&characterEncoding=utf8&serverTimezone=UTC
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# 连接池配置
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
filters: stat,wall,log4j
# 从库配置
slave:
url: jdbc:mysql://localhost:3306/slave_db?useSSL=false&characterEncoding=utf8&serverTimezone=UTC
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# 连接池配置
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
filters: stat,wall,log4j
```
3. 在Java代码中使用ShardingDataSource作为数据源:
```
@Autowired
private DataSource dataSource;
@Bean
public DataSource shardingDataSource() throws SQLException {
return ShardingDataSourceFactory.createDataSource(dataSource);
}
```
使用以上配置后,就可以在Java代码中通过注入shardingDataSource来操作数据库了。
阅读全文