很多情况调用其他服务接口只能接收单一参数,如果系统初始化请求大量数据会受网络延迟的影响,处理这种情况在本系统设置多数据源会获得更好的性能
- 默认Spring Boot会读取
application.properties
中spring.data.source.xxx
作为数据源,但默认配置只能支持单一数据源 - 设置第二个数据源后,默认的配置将不适用,所以设置多数据源不能使用默认的配置
- 配置文件设置
1
2
3
4
5
6
7
8
9
10#database config
spring.datasource.comment.jdbcUrl=
spring.datasource.comment.username=
spring.datasource.comment.password=
spring.datasource.comment.driverClassName=
## user-center datasource
spring.datasource.user-center.jdbcUrl=
spring.datasource.user-center.username=
spring.datasource.user-center.password=
spring.datasource.user-center.driverClassName= - 根据mapper存放地址区分数据源,使用方便
- @ConfigurationProperties可根据配置文件前缀读取属性,并调setter方法将属性注入
@Primary
必须要设置,不然会报错Parameter 0 of method sqlSessionTemplate in tk.mybatis.mapper.autoconfigure.MapperAutoConfiguration required a single bean, but 2 were found:
CommentDataSourceConfiguration
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class CommentDataSourceConfiguration {
public HikariDataSource dataSource() {
return new HikariDataSource();
}
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
public SqlSessionFactory commentSqlSessionFactory( DataSource dataSource)throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
return sessionFactory.getObject();
}
}UserCenterDataSourceConfiguration
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class UserCenterDataSourceConfiguration {
public HikariDataSource dataSource() {
return new HikariDataSource();
}
public DataSourceTransactionManager dataSourceTransactionManager() {
return new DataSourceTransactionManager(dataSource());
}
public SqlSessionFactory userCenterSqlSessionFactory( DataSource dataSource)throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
return sessionFactory.getObject();
}
}
- 配置文件设置