springboot中多数据源配置和使用

不管现实多么惨不忍睹,都要持之以恒地相信,这只是黎明前短暂的黑暗而已。不要惶恐眼前的难关迈不过去,不要担心此刻的付出没有回报,别再花时间等待天降好运。真诚做人,努力做事!你想要的,岁月都会给你。springboot中多数据源配置和使用,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

在日常开发中有时候会涉及到多个数据库的连接和使用,如果项目是使用微服务部署,可以通过增加一个服务来处理数据库连接,如果项目是单体的,这时候就要考虑多数据源的配置了,在springboot中多数据源的配置相对来说还是很简单的,通过几个步骤就可以实现多数据源连接和使用。
项目只使用了mybatis框架,为了演示最原始的配置这里就没有使用mybatis-plus。引入依赖如下:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.11</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.2</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.48</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

接下来就需要在 application.yaml 中做一些配置:

server:
  port: 8081
  shutdown: graceful

spring:
  application:
    name: test-db
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
    locale: zh_CN
  datasource:
    db1:    # 设置数据源1
      jdbc-url: jdbc:mysql://127.0.0.1:3306/db1?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
      driver-class-name: com.mysql.jdbc.Driver
      username: root
      password: 123456@Test
      hikari:
        auto-commit: true            # 自动提交
        connection-timeout: 30000    # 连接超时时间
        idle-timeout: 30000          # 连接池空闲连接回收时间
        minimum-idle: 1              # 最小链接数
        maximum-pool-size: 4         # 最大连接数
        max-lifetime: 1800000        # 线程最大存活时间
        connection-test-query: SELECT A FROM T_POOLPING  # 配置检查连接
    db2:    # 设置数据源2
      jdbc-url: jdbc:mysql://127.0.0.1:3306/db2?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
      driver-class-name: com.mysql.jdbc.Driver
      username: root
      password: 123456@Test
      hikari:
        auto-commit: true            # 自动提交
        connection-timeout: 30000    # 连接超时时间
        idle-timeout: 30000          # 连接池空闲连接回收时间
        minimum-idle: 1              # 最小链接数
        maximum-pool-size: 8         # 最大连接数
        max-lifetime: 1800000        # 线程最大存活时间
        connection-test-query: SELECT A FROM T_POOLPING  # 配置检查连接

在上面的datasource节点下增加了两个子配置db1和db2,分别表示两个数据源,接下来要设置两个数据源的配置:
数据源1的配置:

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.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 数据源1配置
 *
 * @Author xingo
 * @Date 2023/11/8
 */
@Configuration
@MapperScan(basePackages = "org.example.mapper.db1", sqlSessionTemplateRef = "db1SqlSessionTemplate")
public class Db1SourceConfig {

    /**
     * 第一个数据源配置
     * @return
     */
    @Bean(name="db1Source")
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    @Primary
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 第一个数据源的会话工厂配置
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "db1SqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("db1Source") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // 指定扫描sql语句xml文件路径
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/db1/*.xml"));
        return bean.getObject();
    }

    /**
     * 第一个数据源的事务
     * @param dataSource
     * @return
     */
    @Bean(name = "db1TransactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("db1Source") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 第一个数据源的会话模板
     * @param sessionFactory
     * @return
     * @throws Exception
     */
    @Bean(name = "db1SqlSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sessionFactory) throws Exception {
        return new SqlSessionTemplate(sessionFactory);
    }
}

数据源2的配置:

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 org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 数据源2配置
 *
 * @Author xingo
 * @Date 2023/11/8
 */
@Configuration
@MapperScan(basePackages = "org.example.mapper.db2", sqlSessionTemplateRef = "db2SqlSessionTemplate")
public class Db2SourceConfig {

    /**
     * 第二个数据源配置
     * @return
     */
    @Bean(name="db2Source")
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 第二个数据源的会话工厂配置
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "db2SqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("db2Source") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // 指定扫描sql语句xml文件路径
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/db2/*.xml"));
        return bean.getObject();
    }

    /**
     * 第二个数据源的事务
     * @param dataSource
     * @return
     */
    @Bean(name = "db2TransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("db2Source") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 第二个数据源的会话模板
     * @param sessionFactory
     * @return
     * @throws Exception
     */
    @Bean(name = "db2SqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sessionFactory) throws Exception {
        return new SqlSessionTemplate(sessionFactory);
    }
}

在上面配置中分别指定了两个不同的数据源,他们用到的配置信息不同,且扫描包的路径也不同,这样就可以在代码中进行区分。
下面通过在两个不同的路径下分别创建两个映射文件方式来验证配置是否生效,在验证之前需要先准备两个数据库同时创建表并注入数据:
数据源1对应的数据:

CREATE TABLE `T_POOLPING`  (
  `A` tinyint(1) NOT NULL,
  PRIMARY KEY (`A`) USING BTREE
);

INSERT INTO `T_POOLPING` VALUES (1);

CREATE TABLE `t_user`  (
  `fid` int NOT NULL,
  `fname` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  PRIMARY KEY (`fid`) USING BTREE
) ENGINE = InnoDB;

INSERT INTO `t_user` VALUES (1, '张三');

数据源2对应的数据:

CREATE TABLE `T_POOLPING`  (
  `A` tinyint(1) NOT NULL,
  PRIMARY KEY (`A`) USING BTREE
);

INSERT INTO `T_POOLPING` VALUES (1);

CREATE TABLE `t_user`  (
  `fid` int NOT NULL,
  `fname` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  PRIMARY KEY (`fid`) USING BTREE
) ENGINE = InnoDB;

INSERT INTO `t_user` VALUES (1, ' 李四');

在项目的resource路径下创建两个目录:mapper/db1和mapper/db2,这两个目录用于存放xml文件,xml中就是用于编写sql语句。
mapper/db1目录下的文件内容:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.example.mapper.db1.User1Mapper">

	<resultMap id="userMap" type="org.example.pojo.User">
		<result property="id" jdbcType="INTEGER" column="fid" />
		<result property="name" jdbcType="VARCHAR" column="fname" />
	</resultMap>

	<select id="findUserById" parameterType="hashmap" resultMap="userMap">
		SELECT * FROM t_user WHERE fid = #{id, jdbcType=INTEGER}
	</select>
</mapper>

mapper/db2目录下的文件内容:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.example.mapper.db2.User2Mapper">

	<resultMap id="userMap" type="org.example.pojo.User">
		<result property="id" jdbcType="INTEGER" column="fid" />
		<result property="name" jdbcType="VARCHAR" column="fname" />
	</resultMap>

	<select id="findUserById" parameterType="hashmap" resultMap="userMap">
		SELECT * FROM t_user WHERE fid = #{id, jdbcType=INTEGER}
	</select>
</mapper>

这里面有一个User类:

import lombok.Data;

/**
 * @Author xingo
 * @Date 2023/11/8
 */
@Data
public class User {

    private int id;
    private String name;
}

再创建两个Mapper文件,对应xml文件:

import org.apache.ibatis.annotations.Mapper;
import org.example.pojo.User;
import org.springframework.stereotype.Component;

/**
 * @Author xingo
 * @Date 2023/11/8
 */
@Component
@Mapper
public interface User1Mapper {

    User findUserById(int id);
}
import org.apache.ibatis.annotations.Mapper;
import org.example.pojo.User;
import org.springframework.stereotype.Component;

/**
 * @Author xingo
 * @Date 2023/11/8
 */
@Component
@Mapper
public interface User2Mapper {

    User findUserById(int id);
}

在项目中要注意调整文件对应的包路径,避免编译问题。
创建一个controller类测试查询数据:

import org.example.mapper.db1.User1Mapper;
import org.example.mapper.db2.User2Mapper;
import org.example.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author xingo
 * @Date 2023/11/8
 */
@RestController
public class DbController {

    @Autowired
    private User1Mapper user1Mapper;
    @Autowired
    private User2Mapper user2Mapper;

    @GetMapping("/get/user1")
    public User getuser1() {
        return user1Mapper.findUserById(1);
    }

    @GetMapping("/get/user2")
    public User getuser2() {
        return user2Mapper.findUserById(1);
    }
}

执行上面的请求会分别得到下面的内容:

请求:http://localhost:8081/get/user1
{
    "id": 1,
    "name": "张三"
}

请求:http://localhost:8081/get/user2
{
    "id": 1,
    "name": " 李四"
}

可见,我们的两个数据源的配置成功了!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/181839.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!