SpringBoot整合mysql、postgres及sqlserver实现多数据源配置实战案例

 更新时间:2023年12月01日 10:38:31   作者:袁久  
在工作中业务的发展或业务数据隔离的场景下,通常需要一个项目中引入多个数据源,但SpringBoot默认的自动化配置是单数据源的,这篇文章主要给大家介绍了关于SpringBoot整合mysql、postgres及sqlserver实现多数据源配置的相关资料,需要的朋友可以参考下

分享一下近期处理的一个小demo,关于配置多数据源实现不同服务之间的数据推送和数据治理。第一次接触到pg库和sqlserver一头雾水,选择了JDBC+mybatis-plus的方式去链接。

1、首先要引入以下依赖

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.12</version>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.10</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.62</version>
		</dependency>
		<!--mysql 驱动-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.22</version>
		</dependency>
		<!--postgresql 驱动-->
		<dependency>
			<groupId>org.postgresql</groupId>
			<artifactId>postgresql</artifactId>
			<scope>runtime</scope>
		</dependency>
		<!--sqlserver 配置-->
		<dependency>
			<groupId>com.microsoft.sqlserver</groupId>
			<artifactId>mssql-jdbc</artifactId>
			<version>9.4.0.jre8</version>
		</dependency>
		<!--//spring默认的jdbc连接-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.13</version>
		</dependency>
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.4.0</version>
		</dependency>
		<dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-base</artifactId>
			<version>4.4.0</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<version>2.7.12</version>
				<configuration>
					<!-- 指定该Main Class为全局的唯一入口 -->
					<mainClass>com.zkgl.ZsjDemoApplication</mainClass>
				</configuration>
				<executions>
					<execution>
						<goals>
							<!--可以把依赖的包都打包到生成的Jar包中 -->
							<goal>repackage</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

2、demo的项目结构如下

3、yml配置文件

server:
  port:3666
spring:
  application:
    name: multiple-data
  datasource:
    show-sql: false
    db1:
      jdbc-url: jdbc:mysql://ip地址:端口/数据库名?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
      username: 数据库账号
      password: 数据库密码
      driver-class-name: com.mysql.cj.jdbc.Driver
    db2:
      jdbc-url: jdbc:postgresql://ip地址:端口/数据库名?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
      username: 数据库账号
      password: 数据库密码
      driver-class-name: org.postgresql.Driver
    db3:
      jdbc-url: jdbc:sqlserver://ip地址:端口;databaseName=数据库名
      username: 数据库账号
      password: 数据库密码
      driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver

4、配置类

package com.zkgl.config;

import org.apache.ibatis.session.SqlSessionFactory;
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.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
/**
 * @Author: 袁振豪
 * @Description:
 * @Date: Created in  2023-07-23 11:04 PM
 * @Modified By:
 */
@Configuration
@MapperScan(basePackages = "com.zkgl.dao.db1",sqlSessionFactoryRef = "db1SqlSessionFactory")
public class MysqlDataSourceConfig {
    static final String MAPPER_LOCATION = "classpath:/mapper/db1/*.xml";
    @Bean("db1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    public DataSource getDb1DataSource(){
        return DataSourceBuilder.create().build();
    }
    @Bean("db1SqlSessionFactory")
    public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        return bean.getObject();
    }
    @Bean("db1SqlSessionTemplate")
    public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
package com.zkgl.config;

import org.apache.ibatis.session.SqlSessionFactory;
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.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
/**
 * @Author: 袁振豪
 * @Description:
 * @Date: Created in  2023-07-23 11:04 PM
 * @Modified By:
 */
@Configuration
@MapperScan(basePackages = "com.zkgl.dao.db2",sqlSessionFactoryRef = "db2SqlSessionFactory")
public class PgDataSourceConfig {

    static final String MAPPER_LOCATION = "classpath:/mapper/db2/*.xml";
    @Bean("db2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource getDb2DataSource(){
        return DataSourceBuilder.create().build();
    }
    @Bean("db2SqlSessionFactory")
    public SqlSessionFactory db2SqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        return bean.getObject();
    }
    @Bean("db2SqlSessionTemplate")
    public SqlSessionTemplate db2SqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
package com.zkgl.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: 袁振豪
 * @Description:
 * @Date: Created in  2023-07-23 11:04 PM
 * @Modified By:
 */
@Configuration
@MapperScan(basePackages = "com.zkgl.dao.db3",sqlSessionFactoryRef = "db3SqlSessionFactory")
public class SqlServerDataSourceConfig {
    static final String MAPPER_LOCATION = "classpath:/mapper/db3/*.xml";
    @Bean("db3DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db3")
    public DataSource getDb1DataSource(){
        return DataSourceBuilder.create().build();
    }
    @Bean("db3SqlSessionFactory")
    public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db3DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        return bean.getObject();
    }
    @Bean("db3SqlSessionTemplate")
    public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db3SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

5、controller、dao、service以及对应的.xml文件可以根据自身业务情况进行开发,再次不做过多赘述。

总结:要进行多数据源的配置,以此案例为例,最重要的是对各个库的适配,也就是各自的驱动。众所周知,要使用JDBC连接数据库,主要有以下步骤:

  • 注册驱动
  • 建立数据库连接
  • 创建数据库操作对象
  • 执行SQL语句
  • 处理查询结果集
  • 关闭资源 

而在本案例中,pom中引入了相关依赖,在yml配置了驱动,之后在config中以Bean的形式分别命名和初始化相关配置,这样在Springboot项目中,通过@SpringBootApplication注解中的@EnableAutoConfigtion注解就可以扫描到这些配置好的Bean,从而正常使用了。

总结

到此这篇关于SpringBoot整合mysql、postgres及sqlserver实现多数据源配置的文章就介绍到这了,更多相关SpringBoot多数据源配置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Logback动态修改日志级别的方法

    Logback动态修改日志级别的方法

    这篇文章主要介绍了Logback动态修改日志级别的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-11-11
  • eclipse报错 eclipse启动报错解决方法

    eclipse报错 eclipse启动报错解决方法

    本文将介绍eclipse启动报错解决方法,需要了解的朋友可以参考下
    2012-11-11
  • Java+MySQL实现设计优惠券系统

    Java+MySQL实现设计优惠券系统

    这篇文章主要介绍了Java+MySQL实现设计优惠券系统,文章基于Java与MySQL的相关资料展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-05-05
  • 运用Spring Aop+注解实现日志记录

    运用Spring Aop+注解实现日志记录

    我们都知道Spring框架的两大特性分别是 IOC (控制反转)和 AOP (面向切面),这个是每一个Spring学习视频里面一开始都会提到的,这里,如果我们使用Aop来记录日志,那是再好不过了,感兴趣的朋友跟随小编一起学习下Spring Aop注解实现日志记录的过程吧
    2022-01-01
  • Java简易学生成绩系统写法实例

    Java简易学生成绩系统写法实例

    在本篇文章里小编给大家分享的是关于Java简易学生成绩系统写法实例以及相关知识点,有需要的朋友们可以学习下。
    2019-09-09
  • java脚本使用不同版本jdk的说明介绍

    java脚本使用不同版本jdk的说明介绍

    本文介绍了在Java中执行JavaScript脚本的几种方式,包括使用ScriptEngine、Nashorn和GraalVM,ScriptEngine适用于JDK8及以下版本,而Nashorn和GraalVM分别推荐在JDK8及以上和JDK11及以上使用,后者支持更多语言并性能更优
    2025-01-01
  • Java分形绘制山脉模型

    Java分形绘制山脉模型

    这篇文章主要为大家详细介绍了Java分形绘制山脉模型,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • java 对文件夹目录进行深度遍历实例代码

    java 对文件夹目录进行深度遍历实例代码

    这篇文章主要介绍了java 对文件夹目录进行深度遍历实例代码的相关资料,需要的朋友可以参考下
    2017-03-03
  • response.setContentType()参数以及作用详解

    response.setContentType()参数以及作用详解

    这篇文章主要介绍了response.setContentType()参数以及作用详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • java json字符串转JSONObject和JSONArray以及取值的实例

    java json字符串转JSONObject和JSONArray以及取值的实例

    这篇文章主要介绍了java json字符串转JSONObject和JSONArray以及取值的实例的相关资料,需要的朋友可以参考下
    2017-05-05

最新评论