项目中用到了多数据源的问题,在此将自己项目中使用到的技术做一下记录。
pom文件:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<!--有可能项目中的其他依赖包含以下两依赖,如果引入下面的java文件不报错,则忽略如下依赖-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.13</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.3</version>
</dependency>
yml文件:
spring:
datasource:
druid:
#configure jdbc
url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8
username: root
password: 123456
# driver-class-name: com.mysql.jdbc.Driver
#configure connection pooling
initial-size: 5
min-idle: 5
max-active: 50
custom:
datasource:
names: ds1,ds2
ds1:
#configure jdbc
url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8
username: root
password: 123456
# driver-class-name: com.mysql.jdbc.Driver
#configure connection pooling
# initial-size: 5
# min-idle: 5
# max-active: 50
ds2:
# driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
url: jdbc:sqlserver://127.0.0.1:1433;DatabaseName=test
username: sa
password: A123456$
# driver-class-name: com.mysql.jdbc.Driver
#configure connection pooling
# initial-size: 5
# min-idle: 5
# max-active: 50
动态数据源配置文件:
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* Created by Newx on 2017/10/21.
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceContextHolder.getDataSourceType();
}
}
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj