springboot整合多數(shù)據(jù)源配置方式
簡(jiǎn)介
主要介紹兩種整合方式,分別是 springboot+mybatis 使用分包方式整合,和 springboot+druid+mybatisplus 使用注解方式整合。
一、表結(jié)構(gòu)
在本地新建兩個(gè)數(shù)據(jù)庫(kù),名稱(chēng)分別為db1
和db2
,新建一張user
表,表結(jié)構(gòu)如下:
SQL代碼:
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵', `name` varchar(25) NOT NULL COMMENT '姓名', `age` int(2) DEFAULT NULL COMMENT '年齡', `sex` tinyint(1) NOT NULL DEFAULT '0' COMMENT '性別:0-男,1-女', `addr` varchar(100) DEFAULT NULL COMMENT '地址', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
二、多數(shù)據(jù)源整合
1. springboot+mybatis使用分包方式整合
1.1 主要依賴(lài)包
- spring-boot-starter-web
- mybatis-spring-boot-starter
- mysql-connector-java
- lombok
pom.xml
文件如下:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>multipledatasource</artifactId> <version>0.0.1-SNAPSHOT</version> <name>multipledatasource</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!-- spring 依賴(lài) --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- mysql 依賴(lài) --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
1.2 application.yml 配置文件
server: port: 8080 # 啟動(dòng)端口 spring: datasource: db1: # 數(shù)據(jù)源1 jdbc-url: jdbc:mysql://localhost:3306/db1?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver db2: # 數(shù)據(jù)源2 jdbc-url: jdbc:mysql://localhost:3306/db2?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver
注意事項(xiàng)
各個(gè)版本的 springboot 配置 datasource 時(shí)參數(shù)有所變化,例如低版本配置數(shù)據(jù)庫(kù) url 時(shí)使用 url 屬性,高版本使用 jdbc-url 屬性,請(qǐng)注意區(qū)分。
1.3 建立連接數(shù)據(jù)源的配置文件
第一個(gè)配置文件
@Configuration @MapperScan(basePackages = "com.example.multipledatasource.mapper.db1", sqlSessionFactoryRef = "db1SqlSessionFactory") public class DataSourceConfig1 { @Primary // 表示這個(gè)數(shù)據(jù)源是默認(rèn)數(shù)據(jù)源, 這個(gè)注解必須要加,因?yàn)椴患拥脑?huà)spring將分不清楚那個(gè)為主數(shù)據(jù)源(默認(rèn)數(shù)據(jù)源) @Bean("db1DataSource") @ConfigurationProperties(prefix = "spring.datasource.db1") //讀取application.yml中的配置參數(shù)映射成為一個(gè)對(duì)象 public DataSource getDb1DataSource(){ return DataSourceBuilder.create().build(); } @Primary @Bean("db1SqlSessionFactory") public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); // mapper的xml形式文件位置必須要配置,不然將報(bào)錯(cuò):no statement (這種錯(cuò)誤也可能是mapper的xml中,namespace與項(xiàng)目的路徑不一致導(dǎo)致) bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/db1/*.xml")); return bean.getObject(); } @Primary @Bean("db1SqlSessionTemplate") public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory){ return new SqlSessionTemplate(sqlSessionFactory); } }
第二個(gè)配置文件
@Configuration @MapperScan(basePackages = "com.example.multipledatasource.mapper.db2", sqlSessionFactoryRef = "db2SqlSessionFactory") public class DataSourceConfig2 { @Bean("db2DataSource") @ConfigurationProperties(prefix = "spring.datasource.db2") public DataSource getDb1DataSource(){ return DataSourceBuilder.create().build(); } @Bean("db2SqlSessionFactory") public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/db2/*.xml")); return bean.getObject(); } @Bean("db2SqlSessionTemplate") public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory){ return new SqlSessionTemplate(sqlSessionFactory); } }
1.4 具體實(shí)現(xiàn)
項(xiàng)目結(jié)構(gòu)如下:
注意事項(xiàng)
- 在 service 層中根據(jù)不同的業(yè)務(wù)注入不同的 dao 層
- 如果是主從復(fù)制- -讀寫(xiě)分離:比如 db1 中負(fù)責(zé)增刪改,db2 中負(fù)責(zé)查詢(xún)。但是需要注意的是負(fù)責(zé)增刪改的數(shù)據(jù)庫(kù)必須是主庫(kù)(master)
2. springboot+druid+mybatisplus使用注解整合
2.1 主要依賴(lài)包
- spring-boot-starter-web
- mybatis-plus-boot-starter
- dynamic-datasource-spring-boot-starter # 配置動(dòng)態(tài)數(shù)據(jù)源
- druid-spring-boot-starter # 阿里的數(shù)據(jù)庫(kù)連接池
- mysql-connector-java
- lombok
pom.xml
文件如下:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>mutipledatasource2</artifactId> <version>0.0.1-SNAPSHOT</version> <name>mutipledatasource2</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>2.5.6</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.20</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <profiles> <profile> <id>local1</id> <properties> <profileActive>local1</profileActive> </properties> <activation> <activeByDefault>true</activeByDefault> </activation> </profile> <profile> <id>local2</id> <properties> <profileActive>local2</profileActive> </properties> </profile> </profiles> </project>
2.2 application.yml 配置文件
server: port: 8080 spring: datasource: dynamic: primary: db1 # 配置默認(rèn)數(shù)據(jù)庫(kù) datasource: db1: # 數(shù)據(jù)源1配置 url: jdbc:mysql://localhost:3306/db1?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver db2: # 數(shù)據(jù)源2配置 url: jdbc:mysql://localhost:3306/db2?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver durid: initial-size: 1 max-active: 20 min-idle: 1 max-wait: 60000 autoconfigure: exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure # 去除druid配置
DruidDataSourceAutoConfigure
會(huì)注入一個(gè)DataSourceWrapper
,其會(huì)在原生的spring.datasource
下找 url, username, password 等。動(dòng)態(tài)數(shù)據(jù)源 URL 等配置是在 dynamic 下,因此需要排除,否則會(huì)報(bào)錯(cuò)。排除方式有兩種,一種是上述配置文件排除,還有一種可以在項(xiàng)目啟動(dòng)類(lèi)排除:
@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
2.3 給使用非默認(rèn)數(shù)據(jù)源添加注解@DS
@DS
可以注解在方法上和類(lèi)上,同時(shí)存在方法注解優(yōu)先于類(lèi)上注解。
注解在 service 實(shí)現(xiàn)或 mapper 接口方法上,不要同時(shí)在 service 和 mapper 注解。
@DS("db2") public interface UserMapper extends BaseMapper<User> { } @Service @DS("db2") public class ModelServiceImpl extends ServiceImpl<ModelMapper, Model> implements IModelService {} @Select("SELECT * FROM user") @DS("db2") List<User> selectAll();
到此這篇關(guān)于springboot整合多數(shù)據(jù)源配置的文章就介紹到這了,更多相關(guān)springboot整合多數(shù)據(jù)源內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring?Boot集成LiteFlow規(guī)則引擎的詳細(xì)過(guò)程
本文詳細(xì)介紹了如何在Spring?Boot應(yīng)用程序中集成LiteFlow規(guī)則引擎,并探討如何使用LiteFlow庫(kù)來(lái)實(shí)現(xiàn)業(yè)務(wù)流程的規(guī)則處理,將通過(guò)具體的示例來(lái)展示如何在Spring?Boot應(yīng)用程序中配置和使用LiteFlow規(guī)則引擎,以提高系統(tǒng)的靈活性和可維護(hù)性,感興趣的朋友跟隨小編一起看看吧2024-07-07SpringCloud Finchley+Spring Boot 2.0 集成Consul的方法示例(1.2版本)
這篇文章主要介紹了SpringCloud Finchley+Spring Boot 2.0 集成Consul的方法示例(1.2版本),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-08-08springcloud gateway設(shè)置context-path的操作
這篇文章主要介紹了springcloud gateway設(shè)置context-path的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07PowerJobAutoConfiguration自動(dòng)配置源碼流程解析
這篇文章主要為大家介紹了PowerJobAutoConfiguration自動(dòng)配置源碼流程解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12idea解決springboot中的依賴(lài)版本沖突問(wèn)題
這篇文章主要介紹了idea解決springboot中的依賴(lài)版本沖突問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05手把手帶你理解java線(xiàn)程池之工作隊(duì)列workQueue
這篇文章主要介紹了java線(xiàn)程池之工作隊(duì)列workQueue,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-09-09IntelliJ IDEA代碼縮進(jìn)與Tab設(shè)置的操作指南
在軟件開(kāi)發(fā)中,代碼風(fēng)格的統(tǒng)一性直接影響團(tuán)隊(duì)協(xié)作效率與代碼可讀性,IntelliJ IDEA 作為主流 Java 開(kāi)發(fā)工具,提供了高度靈活的 Tabs and Indents 設(shè)置,允許開(kāi)發(fā)者根據(jù)團(tuán)隊(duì)規(guī)范或個(gè)人偏好自定義縮進(jìn)行為,本文給大家介紹了IntelliJ IDEA代碼縮進(jìn)與Tab設(shè)置的操作指南2025-05-05