springboot整合多数据源配置方式

网友投稿 312 2022-11-11

springboot整合多数据源配置方式

目录简介一、表结构二、多数据源整合1. springboot+mybatis使用分包方式整合1.1 主要依赖包1.2 application.yml 配置文件1.3 建立连接数据源的配置文件1.4 具体实现2. springboot+druid+mybatisplus使用注解整合2.1 主要依赖包2.2 application.yml 配置文件2.3 给使用非默认数据源添加注解@DS

简介

主要介绍两种整合方式,分别是 springboot+mybatis 使用分包方式整合,和 springboot+druid+mybatisplus 使用注解方式整合。

一、表结构

在本地新建两个数据库,名称分别为db1和db2,新建一张user表,表结构如下:

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

二、多数据源整合

1. springboot+mybatis使用分包方式整合

1.1 主要依赖包

spring-boot-starter-web

mybatis-spring-boot-starter

mysql-connector-java

lombok

pom.xml 文件如下:

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.1.9.RELEASE

com.example

multipledatasource

0.0.1-SNAPSHOT

multipledatasource

Demo project for Spring Boot

1.8

org.springframework.boot

spring-boot-starter-web

org.mybatis.spring.boot

mybatis-spring-boot-starter

2.1.0

mysql

mysql-connector-java

runtime

org.projectlombok

lombok

true

org.springframework.boot

spring-boot-starter-test

test

http://

org.springframework.boot

spring-boot-maven-plugin

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.1.9.RELEASE

com.example

multipledatasource

0.0.1-SNAPSHOT

multipledatasource

Demo project for Spring Boot

1.8

org.springframework.boot

spring-boot-starter-web

org.mybatis.spring.boot

mybatis-spring-boot-starter

2.1.0

mysql

mysql-connector-java

runtime

org.projectlombok

lombok

true

org.springframework.boot

spring-boot-starter-test

test

http://

org.springframework.boot

spring-boot-maven-plugin

1.2 application.yml 配置文件

server:

port: 8080 # 启动端口

spring:

datasource:

db1: # 数据源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: # 数据源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

注意事项

各个版本的 springboot 配置 datasource 时参数有所变化,例如低版本配置数据库 url 时使用 url 属性,高版本使用 jdbc-url 属性,请注意区分。

1.3 建立连接数据源的配置文件

第一个配置文件

@Configuration

@MapperScan(basePackages = "com.example.multipledatasource.mapper.db1", sqlSessionFactoryRef = "db1SqlSessionFactory")

public class DataSourceConfig1 {

@Primary // 表示这个数据源是默认数据源, 这个注解必须要加,因为不加的话spring将分不清楚那个为主数据源(默认数据源)

@Bean("db1DataSource")

@ConfigurationProperties(prefix = "spring.datasource.db1") //读取application.yml中的配置参数映射成为一个对象

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形式文件位置必须要配置,不然将报错:no statement (这种错误也可能是mapper的xml中,namespace与项目的路径不一致导致)

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);

}

}

第二个配置文件

@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 具体实现

项目结构如下:

注意事项

在 service 层中根据不同的业务注入不同的 dao 层

如果是主从复制- -读写分离:比如 db1 中负责增删改,db2 中负责查询。但是需要注意的是负责增删改的数据库必须是主库(master)

2. springboot+druid+mybatisplus使用注解整合

2.1 主要依赖包

spring-boot-starter-web

mybatis-plus-boot-starter

dynamic-datasource-spring-boot-starter # 配置动态数据源

druid-spring-boot-starter # 阿里的数据库连接池

mysql-connector-java

lombok

pom.xml 文件如下:

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.1.9.RELEASE

com.example

mutipledatasource2

0.0.1-SNAPSHOT

mutipledatasource2

Demo project for Spring Boot

1.8

org.springframework.boot

spring-boot-starter-web

com.baomidou

mybatis-plus-boot-starter

3.2.0

com.baomidou

dynamic-datasource-spring-boot-starter

2.5.6

mysql

mysql-connector-java

runtime

com.alibaba

druid-spring-boot-starter

1.1.20

org.projectlombok

lombok

true

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-maven-plugin

local1

local1

true

local2

local2

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.1.9.RELEASE

com.example

mutipledatasource2

0.0.1-SNAPSHOT

mutipledatasource2

Demo project for Spring Boot

1.8

org.springframework.boot

spring-boot-starter-web

com.baomidou

mybatis-plus-boot-starter

3.2.0

com.baomidou

dynamic-datasource-spring-boot-starter

2.5.6

mysql

mysql-connector-java

runtime

com.alibaba

druid-spring-boot-starter

1.1.20

org.projectlombok

lombok

true

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-maven-plugin

local1

local1

true

local2

local2

2.2 application.yml 配置文件

server:

port: 8080

spring:

datasource:

dynamic:

primary: db1 # 配置默认数据库

datasource:

db1: # 数据源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: # 数据源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会注入一个DataSourceWrapper,其会在原生的spring.datasource下找 url, username, password 等。动态数据源 URL 等配置是在 dynamic 下,因此需要排除,否则会报错。排除方式有两种,一种是上述配置文件排除,还有一种可以在项目启动类排除:

@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)

public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class, args);

}

}

2.3 给使用非默认数据源添加注解@DS

@DS 可以注解在方法上和类上,同时存在方法注解优先于类上注解。

注解在 service 实现或 mapper 接口方法上,不要同时在 service 和 mapper 注解。

@DS("db2")

public interface UserMapper extends BaseMapper {

}

@Service

@DS("db2")

public class ModelServiceImpl extends ServiceImpl implements IModelService {}

@Select("SELECT * FROM user")

@DS("db2")

List selectAll();

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Nginx缓存
下一篇:varnish服务yum安装及不同域名站点
相关文章

 发表评论

暂时没有评论,来抢沙发吧~