springboot+mybatis 配置雙資料來源(mysql,oracle,sqlserver,db2)
阿新 • • 發佈:2021-12-15
以上如圖為專案資料夾目錄。
1,首先配置application.yml 配置檔案
server: port: 8084 tomcat: uri-encoding: utf-8 servlet: context-path: /services #spring: # datasource: # type: com.alibaba.druid.pool.DruidDataSource # # name: skynet # driver-class-name: com.mysql.jdbc.Driver # url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false# username: root # password: root # # # jpa: # show-sql: true #是否在控制檯列印sql語句 # 自定義的mysql主資料來源配置資訊 primary: datasource: #druid相關配置 druid: #監控統計攔截的filters filters: stat driverClassName: com.mysql.jdbc.Driver #配置基本屬性 url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8username: root password: root #配置初始化大小/最小/最大 initialSize: 1 minIdle: 1 maxActive: 20 #獲取連線等待超時時間 maxWait: 60000 #間隔多久進行一次檢測,檢測需要關閉的空閒連線 timeBetweenEvictionRunsMillis: 60000 #一個連線在池中最小生存的時間 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT'x' testWhileIdle: true testOnBorrow: false testOnReturn: false #開啟PSCache,並指定每個連線上PSCache的大小。oracle設為true,mysql設為false。分庫分表較多推薦設定為false poolPreparedStatements: false maxPoolPreparedStatementPerConnectionSize: 20 # 自定義的sqlserver資料來源配置資訊 或者oracle, db2 資料庫,只需要更改driverClassName以及資料庫基本屬性 back: datasource: #druid相關配置 druid: #監控統計攔截的filters filters: stat driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver #配置基本屬性 url: jdbc:sqlserver://127.0.0.1:1433;DatabaseName=tiuweb_drgs username: admin password: 123 #配置初始化大小/最小/最大 initialSize: 1 minIdle: 1 maxActive: 20 #獲取連線等待超時時間 maxWait: 60000 #間隔多久進行一次檢測,檢測需要關閉的空閒連線 timeBetweenEvictionRunsMillis: 60000 #一個連線在池中最小生存的時間 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false #開啟PSCache,並指定每個連線上PSCache的大小。oracle設為true,mysql設為false。分庫分表較多推薦設定為false poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 jackson: time-zone: GMT+8 date-format: yyyy-MM-dd HH:mm:ss resources: static-locations: classpath:/static/,classpath:/views/ #mybatis mybatis: mapper-locations: classpath:mapper/**/*.xml configuration: map-underscore-to-camel-case: true default-fetch-size: 500 default-statement-timeout: 80 # mybatis 分頁外掛 需要配置pom.xml座標 pagehelper: helperDialect: sqlserver reasonable: true supportMethodsArguments: true pageSizeZero: true params: count=countSql #logback日誌配置 需要配置pom.xml座標以及在resources下配置config配置檔案 logging: config: classpath:config/logback-spring.xml level: com.tiuweb.skynet.dao: DEBUG file: path: DRGS_LOG #日誌儲存資料夾
2,配置config資料來源配置檔案PrimaryDataBaseConfig 和BackDataBaseConfig
package com.tw.skynet.config; import com.alibaba.druid.pool.DruidDataSource; import lombok.Data; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.stereotype.Component; import javax.sql.DataSource; import java.sql.SQLException; /** * <p>Title: </p> * <p>Description: TODO * <p> * User: hsy * Date: 2021/11/17 * Time: 15:02 * 修改記錄: * 版本號 修改人 修改日期 修改內容 */ @Data @Configuration @Component // 字首為primary.datasource.druid的配置資訊 @ConfigurationProperties(prefix = "primary.datasource.druid") @MapperScan(basePackages = PrimaryDataBaseConfig.PACKAGE, sqlSessionFactoryRef = "primarySqlSessionFactory") public class PrimaryDataBaseConfig { /** * dao層的包路徑 */ static final String PACKAGE = "com.tw.skynet.dao"; /** * mapper檔案的相對路徑 */ private static final String MAPPER_LOCATION = "classpath:mapper/primary/*.xml"; private String filters; private String url; private String username; private String password; private String driverClassName; private int initialSize; private int minIdle; private int maxActive; private long maxWait; private long timeBetweenEvictionRunsMillis; private long minEvictableIdleTimeMillis; private String validationQuery; private boolean testWhileIdle; private boolean testOnBorrow; private boolean testOnReturn; private boolean poolPreparedStatements; private int maxPoolPreparedStatementPerConnectionSize; // 主資料來源使用@Primary註解進行標識 @Primary @Bean(name = "primaryDataSource") public DataSource primaryDataSource() throws SQLException { DruidDataSource druid = new DruidDataSource(); // 監控統計攔截的filters druid.setFilters(filters); // 配置基本屬性 druid.setDriverClassName(driverClassName); druid.setUsername(username); druid.setPassword(password); druid.setUrl(url); //初始化時建立物理連線的個數 druid.setInitialSize(initialSize); //最大連線池數量 druid.setMaxActive(maxActive); //最小連線池數量 druid.setMinIdle(minIdle); //獲取連線時最大等待時間,單位毫秒。 druid.setMaxWait(maxWait); //間隔多久進行一次檢測,檢測需要關閉的空閒連線 druid.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); //一個連線在池中最小生存的時間 druid.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); //用來檢測連線是否有效的sql druid.setValidationQuery(validationQuery); //建議配置為true,不影響效能,並且保證安全性。 druid.setTestWhileIdle(testWhileIdle); //申請連線時執行validationQuery檢測連線是否有效 druid.setTestOnBorrow(testOnBorrow); druid.setTestOnReturn(testOnReturn); //是否快取preparedStatement,也就是PSCache,oracle設為true,mysql設為false。分庫分表較多推薦設定為false druid.setPoolPreparedStatements(poolPreparedStatements); // 開啟PSCache時,指定每個連線上PSCache的大小 druid.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize); return druid; } // 建立該資料來源的事務管理 @Primary @Bean(name = "primaryTransactionManager") public DataSourceTransactionManager primaryTransactionManager() throws SQLException { return new DataSourceTransactionManager(primaryDataSource()); } // 建立Mybatis的連線會話工廠例項 @Primary @Bean(name = "primarySqlSessionFactory") public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource primaryDataSource) throws Exception { final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(primaryDataSource); // 設定資料來源bean sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver() .getResources(PrimaryDataBaseConfig.MAPPER_LOCATION)); // 設定mapper檔案路徑 return sessionFactory.getObject(); } }
package com.tw.skynet.config; /** * <p>Title: </p> * <p>Description: TODO * <p> * User: hsy * Date: 2021/11/17 * Time: 15:44 * 修改記錄: * 版本號 修改人 修改日期 修改內容 */ import com.alibaba.druid.pool.DruidDataSource; import lombok.Data; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.stereotype.Component; import javax.sql.DataSource; import java.sql.SQLException; /** * @Description: 後臺資料來源配置類 */ @Data @Configuration @Component @ConfigurationProperties(prefix = "back.datasource.druid") @MapperScan(basePackages = BackDataBaseConfig.PACKAGE, sqlSessionFactoryRef = "backSqlSessionFactory") public class BackDataBaseConfig { /** * dao層的包路徑 */ static final String PACKAGE = "com.tw.skynet.dao.back"; /** * mapper檔案的相對路徑 */ private static final String MAPPER_LOCATION = "classpath:mapper/back/*.xml"; private String filters; private String url; private String username; private String password; private String driverClassName; private int initialSize; private int minIdle; private int maxActive; private long maxWait; private long timeBetweenEvictionRunsMillis; private long minEvictableIdleTimeMillis; private String validationQuery; private boolean testWhileIdle; private boolean testOnBorrow; private boolean testOnReturn; private boolean poolPreparedStatements; private int maxPoolPreparedStatementPerConnectionSize; @Bean(name = "backDataSource") public DataSource backDataSource() throws SQLException { DruidDataSource druid = new DruidDataSource(); // 監控統計攔截的filters druid.setFilters(filters); // 配置基本屬性 druid.setDriverClassName(driverClassName); druid.setUsername(username); druid.setPassword(password); druid.setUrl(url); //初始化時建立物理連線的個數 druid.setInitialSize(initialSize); //最大連線池數量 druid.setMaxActive(maxActive); //最小連線池數量 druid.setMinIdle(minIdle); //獲取連線時最大等待時間,單位毫秒。 druid.setMaxWait(maxWait); //間隔多久進行一次檢測,檢測需要關閉的空閒連線 druid.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); //一個連線在池中最小生存的時間 druid.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); //用來檢測連線是否有效的sql druid.setValidationQuery(validationQuery); //建議配置為true,不影響效能,並且保證安全性。 druid.setTestWhileIdle(testWhileIdle); //申請連線時執行validationQuery檢測連線是否有效 druid.setTestOnBorrow(testOnBorrow); druid.setTestOnReturn(testOnReturn); //是否快取preparedStatement,也就是PSCache,oracle設為true,mysql設為false。分庫分表較多推薦設定為false druid.setPoolPreparedStatements(poolPreparedStatements); // 開啟PSCache時,指定每個連線上PSCache的大小 druid.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize); return druid; } @Bean(name = "backTransactionManager") public DataSourceTransactionManager backTransactionManager() throws SQLException { return new DataSourceTransactionManager(backDataSource()); } @Bean(name = "backSqlSessionFactory") public SqlSessionFactory backSqlSessionFactory(@Qualifier("backDataSource") DataSource backDataSource) throws Exception { final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(backDataSource); sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver() .getResources(BackDataBaseConfig.MAPPER_LOCATION)); return sessionFactory.getObject(); } }
3,以上配置就完成了,接下來就是dao資料夾和mapper資料夾分包
現在所有配置已經完了,最後不要忘記pom.xml 匯入所需要的資料庫驅動jar包