SpringBoot实现多数据源配置详解


SpringBoot实现多数据源配置详解

文章插图

开发环境:JDK1.8+SpringBoot2.4.12+Oracle
这里我们假设要使用两个数据源分别为:master和slave 。
  • pom.xml 依赖包
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>com.Github.noraui</groupId><artifactId>ojdbc7</artifactId><version>12.1.0.2</version></dependency><dependency><groupId>org.Apache.commons</groupId><artifactId>commons-lang3</artifactId></dependency><dependency><groupId>org.MyBatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.1.1</version></dependency></dependencies>
  • Application.yml配置
server:port: 50000 ---spring:jpa:hibernate:ddlAuto: updateopenInView: trueshowSql: falsedatabasePlatform: org.hibernate.dialect.Oracle10gDialect---# 第一个数据源master:datasource:driverClassName: oracle.jdbc.driver.OracleDriverurl: jdbc:oracle:thin:@localhost:1521/orclusername: t0password: t0type: com.zaxxer.hikari.HikariDataSourcehikari:minimumIdle: 10maximumPoolSize: 200autoCommit: trueidleTimeout: 30000poolName: MasterDatabookHikariCPmaxLifetime: 1800000connectionTimeout: 30000connectionTestQuery: SELECT 1 FROM DUAL# 第二个数据源slave:datasource:driverClassName: oracle.jdbc.driver.OracleDriverurl: jdbc:oracle:thin:@localhost:1521/orclusername: t1password: t1type: com.zaxxer.hikari.HikariDataSourcehikari:minimumIdle: 10maximumPoolSize: 200autoCommit: trueidleTimeout: 30000poolName: SlaveDatabookHikariCPmaxLifetime: 1800000connectionTimeout: 30000connectionTestQuery: SELECT 1 FROM DUAL---# mybatis 配置 , 分表对应到不同的包中master:mybatis:config-location: classpath:/MyBatis-conf.xmltype-aliases-package: com.pack.domAIn #master数据源对应的包mapper-locations:- classpath:/com/pack/mapper/oracle/*.xml #master数据源对应mapper文件slave:mybatis:config-location: classpath:/MyBatis-conf.xmltype-aliases-package: com.pack.slave.domain #slave数据源对应的包mapper-locations:- classpath:/com/pack/slave/mapper/oracle/*.xml#slave数据源对应mapper文件---# jpa相关的配置master:jpa:repos: com.pack.base.repository #master数据源对应的包配置domain: com.pack.domain #master对应的实体包slave:jpa:repos: com.pack.slave.repository #salve数据源对应的包配置domain: com.pack.slave.domain#slave对应的实体包以上就是两个数据源对应相关的配置了 , 大家注意看里面的注释 。接下来我们看mabatis和jpa对应的类相关的配置了 , 都是固定的配置 。
  • 数据源属性配置对应的JAVA类配置
BaseProperties类
public class BaseDataSourceProperties implements BeanClassLoaderAware, InitializingBean {private ClassLoader classLoader;private String name;private boolean generateUniqueName;private Class<? extends DataSource> type;private String driverClassName;private String url;private String username;private String password;private String jndiName;private DataSourceInitializationMode initializationMode = DataSourceInitializationMode.EMBEDDED;private String platform = "all";private List<String> schema;private String schemaUsername;private String schemaPassword;private List<String> data;private String dataUsername;private String dataPassword;private boolean continueOnError = false;private String separator = ";";private Charset sqlScriptEncoding;private EmbeddedDatabaseConnection embeddedDatabaseConnection = EmbeddedDatabaseConnection.NONE;private Xa xa = new Xa();private String uniqueName;@Overridepublic void setBeanClassLoader(ClassLoader classLoader) {this.classLoader = classLoader;}@Overridepublic void afterPropertiesSet() throws Exception {this.embeddedDatabaseConnection = EmbeddedDatabaseConnection.get(this.classLoader);}public DataSourceBuilder<?> initializeDataSourceBuilder() {return DataSourceBuilder.create(getClassLoader()).type(getType()).driverClassName(determineDriverClassName()).url(determineUrl()).username(determineUsername()).password(determinePassword());}public String getName() {return this.name;}public void setName(String name) {this.name = name;}public boolean isGenerateUniqueName() {return this.generateUniqueName;}public void setGenerateUniqueName(boolean generateUniqueName) {this.generateUniqueName = generateUniqueName;}public Class<? extends DataSource> getType() {return this.type;}public void setType(Class<? extends DataSource> type) {this.type = type;}public String getDriverClassName() {return this.driverClassName;}public void setDriverClassName(String driverClassName) {this.driverClassName = driverClassName;}public String determineDriverClassName() {if (StringUtils.hasText(this.driverClassName)) {Assert.state(driverClassIsLoadable(),() -> "Cannot load driver class: " + this.driverClassName);return this.driverClassName;}String driverClassName = null;if (StringUtils.hasText(this.url)) {driverClassName = DatabaseDriver.fromJdbcUrl(this.url).getDriverClassName();}if (!StringUtils.hasText(driverClassName)) {driverClassName = this.embeddedDatabaseConnection.getDriverClassName();}if (!StringUtils.hasText(driverClassName)) {throw new DataSourceBeanCreationException("Failed to determine a suitable driver class", this,this.embeddedDatabaseConnection);}return driverClassName;}private boolean driverClassIsLoadable() {try {ClassUtils.forName(this.driverClassName, null);return true;}catch (UnsupportedClassVersionError ex) {// Driver library has been compiled with a later JDK, propagate errorthrow ex;}catch (Throwable ex) {return false;}}public String getUrl() {return this.url;}public void setUrl(String url) {this.url = url;}public String determineUrl() {if (StringUtils.hasText(this.url)) {return this.url;}String databaseName = determineDatabaseName();String url = (databaseName != null)? this.embeddedDatabaseConnection.getUrl(databaseName) : null;if (!StringUtils.hasText(url)) {throw new DataSourceBeanCreationException("Failed to determine suitable jdbc url", this,this.embeddedDatabaseConnection);}return url;}public String determineDatabaseName() {if (this.generateUniqueName) {if (this.uniqueName == null) {this.uniqueName = UUID.randomUUID().toString();}return this.uniqueName;}if (StringUtils.hasLength(this.name)) {return this.name;}if (this.embeddedDatabaseConnection != EmbeddedDatabaseConnection.NONE) {return "testdb";}return null;}public String getUsername() {return this.username;}public void setUsername(String username) {this.username = username;}public String determineUsername() {if (StringUtils.hasText(this.username)) {return this.username;}if (EmbeddedDatabaseConnection.isEmbedded(determineDriverClassName())) {return "sa";}return null;}public String getPassword() {return this.password;}public void setPassword(String password) {this.password = password;}public String determinePassword() {if (StringUtils.hasText(this.password)) {return this.password;}if (EmbeddedDatabaseConnection.isEmbedded(determineDriverClassName())) {return "";}return null;}public String getJndiName() {return this.jndiName;}public void setJndiName(String jndiName) {this.jndiName = jndiName;}public DataSourceInitializationMode getInitializationMode() {return this.initializationMode;}public void setInitializationMode(DataSourceInitializationMode initializationMode) {this.initializationMode = initializationMode;}public String getPlatform() {return this.platform;}public void setPlatform(String platform) {this.platform = platform;}public List<String> getSchema() {return this.schema;}public void setSchema(List<String> schema) {this.schema = schema;}public String getSchemaUsername() {return this.schemaUsername;}public void setSchemaUsername(String schemaUsername) {this.schemaUsername = schemaUsername;}public String getSchemaPassword() {return this.schemaPassword;}public void setSchemaPassword(String schemaPassword) {this.schemaPassword = schemaPassword;}public List<String> getData() {return this.data;}public void setData(List<String> data) {this.data = https://www.isolves.com/it/cxkf/jiagou/2023-09-07/data;}public String getDataUsername() {return this.dataUsername;}public void setDataUsername(String dataUsername) {this.dataUsername = dataUsername;}public String getDataPassword() {return this.dataPassword;}public void setDataPassword(String dataPassword) {this.dataPassword = dataPassword;}public boolean isContinueOnError() {return this.continueOnError;}public void setContinueOnError(boolean continueOnError) {this.continueOnError = continueOnError;}public String getSeparator() {return this.separator;}public void setSeparator(String separator) {this.separator = separator;}public Charset getSqlScriptEncoding() {return this.sqlScriptEncoding;}public void setSqlScriptEncoding(Charset sqlScriptEncoding) {this.sqlScriptEncoding = sqlScriptEncoding;}public ClassLoader getClassLoader() {return this.classLoader;}public Xa getXa() {return this.xa;}public void setXa(Xa xa) {this.xa = xa;}public static class Xa {private String dataSourceClassName;private Map


推荐阅读