Spring Boot之JdbcTemplate多数据源配置与使用

之前在介绍使用JdbcTemplate和Spring-data-jpa时,都使用了单数据源。在单数据源的情况下,Spring Boot的配置非常简单,只需要在application.properties文件中配置连接参数即可。但是往往随着业务量发展,我们通常会进行数据库拆分或是引入其他数据库,从而我们需要配置多个数据源,下面基于之前的JdbcTemplate和Spring-data-jpa例子分别介绍两种多数据源的配置方式。

多数据源配置

创建一个Spring配置类,定义两个DataSource用来读取application.properties中的不同配置。如下例子中,主数据源配置为spring.datasource.primary开头的配置,第二数据源配置为spring.datasource.secondary开头的配置。

package com.wls.diypro.util.datasource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@Configuration
public class DataSourceConfig {
    @Bean(name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @ConfigurationProperties(prefix="spring.datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "secondaryDataSource")
    @Qualifier("secondaryDataSource")
    @Primary
    @ConfigurationProperties(prefix="spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "primaryJdbcTemplate")
    public JdbcTemplate primaryJdbcTemplate(
            @Qualifier("primaryDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
    @Bean(name = "secondaryJdbcTemplate")
    public JdbcTemplate secondaryJdbcTemplate(
            @Qualifier("secondaryDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}

  

  

JdbcTemplate支持对应的application-dev.yml配置如下:

spring:
  datasource:
    primary:
      driver-class-name: com.mysql.jdbc.Driver
  #    url: jdbc:mysql://192.168.159.128:3306/mydb
      url: jdbc:mysql://192.168.11.131:3306/mydb
      username: wls
      password: Wls141215!
    secondary:
      driver-class-name: com.mysql.jdbc.Driver
  #    url: jdbc:mysql://192.168.159.128:3306/mydb
      url: jdbc:mysql://192.168.11.131:3306/shopmall
      username: wls
      password: Wls141215!

对JdbcTemplate的支持比较简单,只需要为其注入对应的datasource即可,如下例子,在创建JdbcTemplate的时候分别注入名为primaryDataSourcesecondaryDataSource的数据源来区分不同的JdbcTemplate。

@Autowired
    @Qualifier("primaryJdbcTemplate")
    protected JdbcTemplate primaryJdbcTemplate;

    @Autowired
    @Qualifier("secondaryJdbcTemplate")
    protected JdbcTemplate secondaryJdbcTemplate;

  

package com.wls.diypro.test.jdbcTemplateTest;

import com.wls.diypro.model.OrderInfo;
import com.wls.diypro.service.IOrderInfoService;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Date;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class JdbcTemplateTest {

    @Autowired
    @Qualifier("primaryJdbcTemplate")
    protected JdbcTemplate primaryJdbcTemplate;

    @Autowired
    @Qualifier("secondaryJdbcTemplate")
    protected JdbcTemplate secondaryJdbcTemplate;

    @Autowired
    private IOrderInfoService iOrderInfoService;

    @Test
    public void addOrder() throws Exception {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setAddressDetail("广平大街");
        orderInfo.setArea("大兴区");
        orderInfo.setCity("北京市");
        orderInfo.setOrderNumber("10000001");
        orderInfo.setOrderStatus("2");
        orderInfo.setOrderTime(new Date());
        orderInfo.setProvince("北京");
        orderInfo.setReceiver("王老师");
        orderInfo.setStreet("ces");
        iOrderInfoService.addOrder(orderInfo);
    }

    @Before
    public void setUp() {
        primaryJdbcTemplate.update("DELETE  FROM  order_info ");
        secondaryJdbcTemplate.update("DELETE  FROM  order_info ");
    }

    @Test
    public void test() throws Exception {

        // 往第一个数据源中插入两条数据
        primaryJdbcTemplate.update("insert into order_info(order_flag,order_number,order_status,street) values(?, ?, ?, ?)", "test", "10001", "S01","广平大街");
        primaryJdbcTemplate.update("insert into order_info(order_flag,order_number,order_status,street) values(?, ?, ?, ?)", "test", "10001", "S01","广平大街");

        // 往第二个数据源中插入一条数据,若插入的是第一个数据源,则会主键冲突报错
        secondaryJdbcTemplate.update("insert into order_info(order_flag,order_number,order_status,street) values(?, ?, ?, ?)", "test", "10003", "S02","广平大街");

        // 查一下第一个数据源中是否有两条数据,验证插入是否成功
        Assert.assertEquals("2", primaryJdbcTemplate.queryForObject("select count(1) from order_info", String.class));

        // 查一下第一个数据源中是否有两条数据,验证插入是否成功
        Assert.assertEquals("1", secondaryJdbcTemplate.queryForObject("select count(1) from order_info", String.class));

    }
}

  

完整示例:guithub接下来通过测试用例来演示如何使用这两个针对不同数据源的JdbcTemplate。

时间: 2024-07-30 13:49:28

Spring Boot之JdbcTemplate多数据源配置与使用的相关文章

spring boot 与 JdbcTemplate 一起工作

spring boot 与 JdbcTemplate 一起工作 本文将介绍如何将spring boot 与 JdbcTemplate一起工作. Spring对数据库的操作在jdbc上面做了深层次的封装,使用spring的注入功能,可以把DataSource注册到JdbcTemplate之中. JdbcTemplate 是在JDBC API基础上提供了更抽象的封装,并提供了基于方法注解的事务管理能力. 通过使用SpringBoot自动配置功能并代替我们自动配置beans. 在maven中,我们需要

spring boot与jdbcTemplate的整合案例2

简单入门了spring boot后,接下来写写跟数据库打交道的案例.博文采用spring的jdbcTemplate工具类与数据库打交道. 下面是搭建的springbootJDBC的项目的总体架构图: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www

Spring Boot整合JdbcTemplate访问数据库

这篇文章是介绍 Spring Boot整合JdbcTemplate,配置数据源来访问数据库. 在pom文件里添加 spring-boot-starter-jdbc 和mysql依赖. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId></dependency> <dep

Spring Boot应用的后台运行配置

酱油一篇,整理一下关于Spring Boot后台运行的一些配置方式.在介绍后台运行配置之前,我们先回顾一下Spring Boot应用的几种运行方式: 运行Spring Boot的应用主类 使用Maven的Spring Boot插件mvn spring-boot:run来运行 打成jar包后,使用java -jar运行 我们在开发的时候,通常会使用前两种,而在部署的时候往往会使用第三种.但是,我们在使用java -jar来运行的时候,并非后台运行.下面我们分别针对Windows和Linux/Uni

[转]Spring Boot应用的后台运行配置

转自:http://blog.didispace.com/spring-boot-run-backend/ 酱油一篇,整理一下关于Spring Boot后台运行的一些配置方式.在介绍后台运行配置之前,我们先回顾一下Spring Boot应用的几种运行方式: 运行Spring Boot的应用主类 使用Maven的Spring Boot插件mvn spring-boot:run来运行 打成jar包后,使用java -jar运行 我们在开发的时候,通常会使用前两种,而在部署的时候往往会使用第三种.但是

JAR(Spring Boot)应用的后台运行配置

酱油一篇,整理一下关于Spring Boot后台运行的一些配置方式.在介绍后台运行配置之前,我们先回顾一下Spring Boot应用的几种运行方式: 运行Spring Boot的应用主类 使用Maven的Spring Boot插件mvn spring-boot:run来运行 打成jar包后,使用java -jar运行 我们在开发的时候,通常会使用前两种,而在部署的时候往往会使用第三种.但是,我们在使用java -jar来运行的时候,并非后台运行.下面我们分别针对Windows和Linux/Uni

Spring boot 的 properties 属性值配置 application.properties 与 自定义properties

配置属性值application.properties 文件直接配置: com.ieen.super.name="MDD" 自定义properties文件配置:src/main/resources/conf/boot.properties com.ieen.boot.name="123" com.ieen.boot.value="456" 调用方法@Value 注解调用application.properties属性值: @Value("

spring boot application.properties文件外部配置

spring boot application.properties文件外部配置 官方文档 原文地址:https://www.cnblogs.com/lwmp/p/9836791.html

Spring Boot 启动(二) 配置详解

Spring Boot 启动(二) 配置详解 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) Spring Boot 配置文件加载顺序 Spring Boot 配置文件加载分析 - ConfigFileApplicationListener 一.Spring Framework 配置 略... 二.Spring Boot 配置 2.1 随机数配置 name.value=${random.int} name.int=${