springboot双数据源配置及进行数据库操作
- application.yaml配置文件
spring:datasource:druid:stat-view-servlet:enabled: trueloginUsername: adminloginPassword: 123456dynamic:druid:initial-size: 5min-idle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: truemaxPoolPreparedStatementPerConnectionSize: 20filters: stat,slf4jconnectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000# 设置默认的数据源或者数据源组,默认值即为masterprimary: master# 严格匹配数据源,默认false.true未匹配到指定数据源时抛异常,false使用默认数据源strict: falsedatasource:#人大金仓数据库1master: driver-class-name: com.kingbase8.Driverurl: jdbc:kingbase8://ip:port/test1username: test1password: testpwd#人大金仓数据库2dataCenterDb:driver-class-name: com.kingbase8.Driverurl: jdbc:kingbase8://ip:port/test2?currentSchema=anon1username: test2password: test2pwd
-
处理不同数据库业务
- 处理数据库1
@Service public class LocalDbServiceImpl implements ILocalDbService {@Resourceprivate DataCenterDbMapper dataCenterDbMapper;//@DS("master")//配置文件已设置默认数据库(primary: master),所以这里不配置不影响,默认就是master。在这里面不要调用数据库2的service,不然也会默认是数据库1的操作@Overridepublic 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 {@ResourceILocalDbService localDbService;@ResourceIDataCenterDbService dataCenterDbService;//处理两个不同数据库业务public void test(){localDbService.select();dataCenterDbService.insert();} }