- application.yaml配置文件
spring:
datasource:
druid:
stat-view-servlet:
enabled: true
loginUsername: admin
loginPassword: 123456
dynamic:
druid:
initial-size: 5
min-idle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
filters: stat,slf4j
connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
# 设置默认的数据源或者数据源组,默认值即为master
primary: master
# 严格匹配数据源,默认false.true未匹配到指定数据源时抛异常,false使用默认数据源
strict: false
datasource:
#人大金仓数据库1
master:
driver-class-name: com.kingbase8.Driver
url: jdbc:kingbase8://ip:port/test1
username: test1
password: testpwd
#人大金仓数据库2
dataCenterDb:
driver-class-name: com.kingbase8.Driver
url: jdbc:kingbase8://ip:port/test2?currentSchema=anon1
username: test2
password: test2pwd
处理不同数据库业务
- 处理数据库1
@Service public class LocalDbServiceImpl implements ILocalDbService { @Resource private DataCenterDbMapper dataCenterDbMapper; //@DS("master")//配置文件已设置默认数据库(primary: master),所以这里不配置不影响,默认就是master。在这里面不要调用数据库2的service,不然也会默认是数据库1的操作 @Override public void select(){ return dataCenterDbMapper.select(); } }
- 处理数据库2
@Slf4j @Service public class DataCenterDbServiceImpl implements IDataCenterDbService { @Override @DS("dataCenterDb") //加上该注解,该方法所有涉及到数据库的操作均为dataCenterDb数据库。在这里面不要调用数据库1的service,不然也会默认是数据库2的操作 public void insert(){ log.info("*** 当前数据库:{}", DynamicDataSourceContextHolder.peek()); //处理业务 }
- 处理两个数据库
@Slf4j @Component public class Test { @Resource ILocalDbService localDbService; @Resource IDataCenterDbService dataCenterDbService; //处理两个不同数据库业务 public void test(){ localDbService.select(); dataCenterDbService.insert(); }