shardingsphere+dynamic+mybatisPlugs配置多数据源yml 怎么实现
时间: 2023-12-21 08:05:23 浏览: 103
在ShardingSphere中,可以通过配置多个数据源来实现多数据源的支持。同时,为了支持MyBatis的插件,也需要在配置文件中配置相应的插件。
以下是一个示例配置文件,其中包括两个数据源和对应的MyBatis插件配置:
```yaml
spring:
datasource:
# 第一个数据源配置
ds1:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/db1?useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8
username: root
password: root
# 第二个数据源配置
ds2:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/db2?useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8
username: root
password: root
mybatis:
mapper-locations: classpath*:mapper/*.xml
plugins:
# 插件1配置
- plugin: com.example.plugin.Plugin1
properties:
property1: value1
# 插件2配置
- plugin: com.example.plugin.Plugin2
properties:
property2: value2
```
在代码中,可以通过`@MapperScan`注解来指定扫描的Mapper接口所在的包,同时也可以通过`@Qualifier`注解来指定使用哪个数据源,示例代码如下:
```java
@SpringBootApplication
@MapperScan(basePackages = "com.example.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean(name = "ds1SqlSessionFactory")
@Primary
public SqlSessionFactory ds1SqlSessionFactory(@Qualifier("ds1DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath*:mapper/ds1/*.xml"));
return sessionFactoryBean.getObject();
}
@Bean(name = "ds2SqlSessionFactory")
public SqlSessionFactory ds2SqlSessionFactory(@Qualifier("ds2DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath*:mapper/ds2/*.xml"));
return sessionFactoryBean.getObject();
}
@Bean(name = "ds1DataSource")
@ConfigurationProperties(prefix = "spring.datasource.ds1")
@Primary
public DataSource ds1DataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "ds2DataSource")
@ConfigurationProperties(prefix = "spring.datasource.ds2")
public DataSource ds2DataSource() {
return DataSourceBuilder.create().build();
}
}
```
在上述代码中,`@Primary`注解用于指定默认数据源,可以通过`@Qualifier`注解指定使用哪个数据源,如:
```java
@Autowired
@Qualifier("ds1SqlSessionFactory")
private SqlSessionFactory ds1SqlSessionFactory;
```
这样即可在代码中使用对应的数据源和MyBatis插件。
阅读全文