前言:网上找了很多配置多数据源的,霹雳啪啦一堆不想看,自己写一个简捷版的,因为在实际工作中可能会涉及到多个库或者不同ip地址的数据库,话不多说,直接上代码。
1.项目结构
2.代码实现
1.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.6.13</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.hengbao</groupId>
<!-- 显式声明打包类型为JAR -->
<packaging>jar</packaging>
<artifactId>demo2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo2</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-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 如果需要可执行JAR,移除scope=provided或删除此依赖 -->
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- 配置处理器(关键) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- HikariCP 连接池 -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.hengbao.demo2.Demo2Application</mainClass>
<!-- 启用Spring Boot打包 -->
<skip>false</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
里面这两个依赖记得引入,我们配置多数据源用的到
2.application.properties
其中主要是配置了两个数据库的连接信息
# 禁用自动配置
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
# 主数据源配置
spring.datasource.jdbc-url=jdbc:mysql://localhost:3306/web_service
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
# HikariCP 配置 - 使用标准属性名
spring.datasource.maximum-pool-size=10
spring.datasource.minimum-idle=2
spring.datasource.idle-timeout=30000
spring.datasource.pool-name=PrimaryHikariPool
spring.datasource.max-lifetime=1800000
spring.datasource.connection-timeout=30000
spring.datasource.connection-test-query=SELECT 1
# 从数据源配置
spring.second-datasource.jdbc-url=jdbc:mysql://localhost:3306/second_database
spring.second-datasource.username=root
spring.second-datasource.password=
spring.second-datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.second-datasource.type=com.zaxxer.hikari.HikariDataSource
# HikariCP 配置 - 使用标准属性名
spring.second-datasource.maximum-pool-size=10
spring.second-datasource.minimum-idle=2
spring.second-datasource.idle-timeout=30000
spring.second-datasource.pool-name=SecondaryHikariPool
spring.second-datasource.max-lifetime=1800000
spring.second-datasource.connection-timeout=30000
spring.second-datasource.connection-test-query=SELECT 1
# ====================== MyBatis 配置(可选,若使用全局路径需谨慎)=====================
# 若各数据源Mapper路径独立,建议注释以下全局配置,仅在DataSourceConfig中配置
# mybatis.mapper-locations=classpath:mappers/*.xml
# mybatis.type-aliases-package=com.hengbao.demo2.entity
# 日志配置(可选,用于调试SQL)
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
logging.level.com.hengbao.demo2.mapper=DEBUG
3.DataSourceConfig
这个配置文件主要就是规定了哪个mapper包下的sql语句连哪个数据库,然后数据源的创建初始化
package com.hengbao.demo2.config;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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 javax.sql.DataSource;
@Configuration
@Slf4j
@EnableConfigurationProperties
// 为每个数据源创建单独的 @MapperScan 注解
@MapperScan(basePackages = "com.hengbao.demo2.mapper.primary", sqlSessionTemplateRef = "primarySqlSessionTemplate")
@MapperScan(basePackages = "com.hengbao.demo2.mapper.secondary", sqlSessionTemplateRef = "secondarySqlSessionTemplate")
public class DataSourceConfig {
private final PrimaryDataSourceProperties primaryProps;
private final SecondaryDataSourceProperties secondaryProps;
public DataSourceConfig(PrimaryDataSourceProperties primaryProps,
SecondaryDataSourceProperties secondaryProps) {
this.primaryProps = primaryProps;
this.secondaryProps = secondaryProps;
}
// 主数据源配置(保持不变)
@Primary
@Bean(name = "primaryDataSource")
public DataSource primaryDataSource() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setJdbcUrl(primaryProps.getJdbcUrl());
dataSource.setUsername(primaryProps.getUsername());
dataSource.setPassword(primaryProps.getPassword());
dataSource.setDriverClassName(primaryProps.getDriverClassName());
dataSource.setMaximumPoolSize(primaryProps.getMaximumPoolSize());
dataSource.setMinimumIdle(primaryProps.getMinimumIdle());
dataSource.setIdleTimeout(primaryProps.getIdleTimeout());
dataSource.setPoolName(primaryProps.getPoolName());
dataSource.setMaxLifetime(primaryProps.getMaxLifetime());
dataSource.setConnectionTimeout(primaryProps.getConnectionTimeout());
dataSource.setConnectionTestQuery(primaryProps.getConnectionTestQuery());
log.info("主数据源配置: {}", dataSource.getJdbcUrl());
return dataSource;
}
@Primary
@Bean(name = "primarySqlSessionFactory")
public SqlSessionFactoryBean primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setTypeAliasesPackage("com.hengbao.demo2.entity");
return bean;
}
@Primary
@Bean(name = "primaryTransactionManager")
public DataSourceTransactionManager primaryTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Primary
@Bean(name = "primarySqlSessionTemplate")
public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactoryBean sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory.getObject());
}
// 从数据源配置(保持不变)
@Bean(name = "secondaryDataSource")
public DataSource secondaryDataSource() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setJdbcUrl(secondaryProps.getJdbcUrl());
dataSource.setUsername(secondaryProps.getUsername());
dataSource.setPassword(secondaryProps.getPassword());
dataSource.setDriverClassName(secondaryProps.getDriverClassName());
dataSource.setMaximumPoolSize(secondaryProps.getMaximumPoolSize());
dataSource.setMinimumIdle(secondaryProps.getMinimumIdle());
dataSource.setIdleTimeout(secondaryProps.getIdleTimeout());
dataSource.setPoolName(secondaryProps.getPoolName());
dataSource.setMaxLifetime(secondaryProps.getMaxLifetime());
dataSource.setConnectionTimeout(secondaryProps.getConnectionTimeout());
dataSource.setConnectionTestQuery(secondaryProps.getConnectionTestQuery());
log.info("从数据源配置: {}", dataSource.getJdbcUrl());
return dataSource;
}
@Bean(name = "secondarySqlSessionFactory")
public SqlSessionFactoryBean secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setTypeAliasesPackage("com.hengbao.demo2.entity");
return bean;
}
@Bean(name = "secondaryTransactionManager")
public DataSourceTransactionManager secondaryTransactionManager(@Qualifier("secondaryDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "secondarySqlSessionTemplate")
public SqlSessionTemplate secondarySqlSessionTemplate(@Qualifier("secondarySqlSessionFactory") SqlSessionFactoryBean sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory.getObject());
}
}
4.PrimaryDataSourceProperties 和 SecondaryDataSourceProperties
这两块主要是从配置文件application.properties中读取配置信息并创建到容器中管理
package com.hengbao.demo2.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class PrimaryDataSourceProperties {
private String jdbcUrl;
private String username;
private String password;
private String driverClassName;
private int maximumPoolSize;
private int minimumIdle;
private long idleTimeout;
private String poolName;
private long maxLifetime;
private long connectionTimeout;
private String connectionTestQuery;
}
package com.hengbao.demo2.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "spring.second-datasource")
public class SecondaryDataSourceProperties {
private String jdbcUrl;
private String username;
private String password;
private String driverClassName;
private int maximumPoolSize;
private int minimumIdle;
private long idleTimeout;
private String poolName;
private long maxLifetime;
private long connectionTimeout;
private String connectionTestQuery;
}
5.Demo2Application
这个主要是排除默认数据源配置,使用我们上面自定义的数据源配置
package com.hengbao.demo2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class Demo2Application {
public static void main(String[] args) {
SpringApplication.run(Demo2Application.class, args);
}
}
通过如上配置,我们就在springboot项目中完成了多数源配置,下面我们来测试下
3.数据测试
1.通过democontroller /demo读取的是我们第二个库中的数据
2.通过usercontroller /index.html读取的是我们第一个库中的数据
自此验证成功,代码我放在附件中,需要的自行参考。