pigx配置多个数据源
时间: 2023-07-04 21:09:02 浏览: 211
在pigx中配置多个数据源,需要进行以下步骤:
1. 在application.yml文件中配置数据源信息,如下所示:
```yaml
spring:
datasource:
dynamic:
primary: db1 # 指定默认数据源
datasource:
db1:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db1?useSSL=false&serverTimezone=UTC
username: root
password: root
db2:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db2?useSSL=false&serverTimezone=UTC
username: root
password: root
```
2. 在配置类中动态创建数据源,并将其加入到AbstractRoutingDataSource中,如下所示:
```java
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.dynamic")
public DataSource dataSource() {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
Map<Object, Object> dataSourceMap = new HashMap<>();
DataSource db1 = DataSourceBuilder.create().build();
DataSource db2 = DataSourceBuilder.create().build();
dataSourceMap.put("db1", db1);
dataSourceMap.put("db2", db2);
dynamicDataSource.setTargetDataSources(dataSourceMap);
dynamicDataSource.setDefaultTargetDataSource(db1);
return dynamicDataSource;
}
}
```
3. 创建数据源路由类,继承AbstractRoutingDataSource,重写determineCurrentLookupKey()方法,用于动态获取数据源,如下所示:
```java
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDataSourceKey();
}
}
```
4. 创建数据源上下文类,用于保存当前使用的数据源的key值,如下所示:
```java
public class DataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
public static void setDataSourceKey(String dataSourceKey) {
contextHolder.set(dataSourceKey);
}
public static String getDataSourceKey() {
return contextHolder.get();
}
public static void clearDataSourceKey() {
contextHolder.remove();
}
}
```
5. 在需要使用的地方,通过调用DataSourceContextHolder.setDataSourceKey()方法设置当前使用的数据源,如下所示:
```java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> getUserList() {
DataSourceContextHolder.setDataSourceKey("db1");
return userMapper.getUserList();
}
}
```
以上就是在pigx中配置多个数据源的步骤,希望能够帮助到你。
阅读全文