Java Spring中同时访问多种不同数据库

本文涉及的产品
云原生数据库 PolarDB MySQL 版,Serverless 5000PCU 100GB
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介:

开发企业应用时我们常常遇到要同时访问多种不同数据库的问题,有时是必须把数据归档到某种数据仓库中,有时是要把数据变更推送到第三方数据库中。使用Spring框架时,使用单一数据库是非常容易的,但如果要同时访问多个数据库的话事件就变得复杂多了。

本文以在Spring框架下开发一个SpringMVC程序为例,示范了一种同时访问多种数据库的方法,而且尽量地简化配置改动。

搭建数据库

建议你也同时搭好两个数据库来跟进我们的示例。本文中我们用了PostgreSQL和MySQL。

下面的脚本内容是在两个数据库中建表和插入数据的命令。

PostgreSQL

 
  1. CREATE TABLE usermaster (  
  2.    id integer,  
  3.    name character varying,  
  4.    emailid character varying,  
  5.    phoneno character varying(10),  
  6.    location character varying)  
  7.  
  8. INSERT INTO usermaster(id, name, emailid, phoneno, location)VALUES (1, 'name_postgres', 'email@email.com', '1234567890', 'IN');  

MySQL

 
  1. CREATE TABLE `usermaster` (   `id` int(11) NOT NULL,  
  2.    `name` varchar(255) DEFAULT NULL,  
  3.    `emailid` varchar(20) DEFAULT NULL,  
  4.    `phoneno` varchar(20) DEFAULT NULL,  
  5.    `location` varchar(20) DEFAULT NULL,  
  6.    PRIMARY KEY (`id`)  
  7. )INSERT INTO `kode12`.`usermaster`  
  8.   (`id`, `name`, `emailid`, `phoneno`, `location`)VALUES 
  9.   ('1', 'name_mysql', 'test@tset.com', '9876543210', 'IN');  

搭建项目

我们用Spring Tool Suite (STS)来构建这个例子:

点击File -> New -> Spring Starter Project。

在对话框中输入项目名、Maven坐标、描述和包信息等,点击Next。

在boot dependency中选择Web,点击Next。

点击Finish。STS会自动按照项目依赖关系从Spring仓库中下载所需要的内容。

创建完的项目如下图所示:

接下来我们仔细研究一下项目中的各个相关文件内容。

pom.xml

pom中包含了所有需要的依赖和插件映射关系。

代码:

 
  1. <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  3.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0  
  4.     http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
  5.     <modelVersion>4.0.0</modelVersion> 
  6.  
  7.     <groupId>com.aegis</groupId> 
  8.     <artifactId>MultipleDBConnect</artifactId> 
  9.     <version>0.0.1-SNAPSHOT</version> 
  10.     <packaging>jar</packaging> 
  11.  
  12.     <name>MultipleDB</name> 
  13.     <description>MultipleDB with Spring Boot</description> 
  14.  
  15.     <parent> 
  16.         <groupId>org.springframework.boot</groupId> 
  17.         <artifactId>spring-boot-starter-parent</artifactId> 
  18.         <version>1.3.5.RELEASE</version> 
  19.         <relativePath /> 
  20.     </parent> 
  21.  
  22.     <properties> 
  23.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
  24.         <java.version>1.8</java.version> 
  25.     </properties> 
  26.  
  27.     <dependencies> 
  28.         <dependency> 
  29.             <groupId>org.springframework.boot</groupId> 
  30.             <artifactId>spring-boot-starter-web</artifactId> 
  31.         </dependency> 
  32.  
  33.         <dependency> 
  34.             <groupId>org.springframework.boot</groupId> 
  35.             <artifactId>spring-boot-starter-test</artifactId> 
  36.             <scope>test</scope> 
  37.         </dependency> 
  38.  
  39.         <dependency> 
  40.             <groupId>org.springframework.boot</groupId> 
  41.             <artifactId>spring-boot-starter-jdbc</artifactId> 
  42.         </dependency> 
  43.  
  44.         <dependency> 
  45.             <groupId>org.postgresql</groupId> 
  46.             <artifactId>postgresql</artifactId> 
  47.         </dependency> 
  48.  
  49.         <dependency> 
  50.             <groupId>mysql</groupId> 
  51.             <artifactId>mysql-connector-java</artifactId> 
  52.             <version>5.1.38</version> 
  53.         </dependency> 
  54.     </dependencies> 
  55.  
  56.     <build> 
  57.         <plugins> 
  58.             <plugin> 
  59.                 <groupId>org.springframework.boot</groupId> 
  60.                 <artifactId>spring-boot-maven-plugin</artifactId> 
  61.             </plugin> 
  62.         </plugins> 
  63.     </build></project>  

解释:

下面详细解释各种依赖关系的细节:

spring-boot-starter-web:为Web开发和MVC提供支持。

spring-boot-starter-test:提供JUnit、Mockito等测试依赖。

spring-boot-starter-jdbc:提供JDBC支持。

postgresql:PostgreSQL数据库的JDBC驱动。

mysql-connector-java:MySQL数据库的JDBC驱动。

application.properties

包含程序需要的所有配置信息。在旧版的Spring中我们要通过多个XML文件来提供这些配置信息。

 
  1. server.port=6060spring.ds_post.url =jdbc:postgresql://localhost:5432/kode12spring.ds_post.username =postgres 
  2. spring.ds_post.password =root 
  3. spring.ds_post.driverClassName=org.postgresql.Driverspring.ds_mysql.url = jdbc:mysql://localhost:3306/kode12spring.ds_mysql.username = root 
  4. spring.ds_mysql.password = root 
  5. spring.ds_mysql.driverClassName=com.mysql.jdbc.Driver  

解释:

“server.port=6060”声明你的嵌入式服务器启动后会使用6060端口(port.server.port是Boot默认的标准端口)。

其他属性中:

以“spring.ds_*”为前缀的是用户定义属性。

以“spring.ds_post.*”为前缀的是为PostgreSQL数据库定义的属性。

以“spring.ds_mysql.*”为前缀的是为MySQL数据库定义的属性。

MultipleDbApplication.java

 
  1. package com.aegis;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic MultipleDbApplication {    public static void main(String[] args) { 
  2.         SpringApplication.run(MultipleDbApplication.class, args); 
  3.     } 

这个文件包含了启动我们的Boot程序的主函数。注解“@SpringBootApplication”是所有其他Spring注解和Java注解的组合,包括:

 
  1. @Configuration@EnableAutoConfiguration@ComponentScan@Target(value={TYPE})@Retention(value=RUNTIME)@Documented@Inherited 

其他注解:

 
  1. @Configuration@EnableAutoConfiguration@ComponentScan 

上述注解会让容器通过这个类来加载我们的配置。

MultipleDBConfig.java

 
  1. package com.aegis.config;import javax.sql.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; 
  2.  
  3. @Configurationpublic class MultipleDBConfig { 
  4.     @Bean(name = "mysqlDb") 
  5.     @ConfigurationProperties(prefix = "spring.ds_mysql") 
  6.     public DataSource mysqlDataSource() {        return DataSourceBuilder.create().build(); 
  7.     } 
  8.  
  9.     @Bean(name = "mysqlJdbcTemplate") 
  10.     public JdbcTemplate jdbcTemplate(@Qualifier("mysqlDb") DataSource dsMySQL) {        return new JdbcTemplate(dsMySQL); 
  11.     } 
  12.  
  13.     @Bean(name = "postgresDb") 
  14.     @ConfigurationProperties(prefix = "spring.ds_post") 
  15.     public DataSource postgresDataSource() {        return  DataSourceBuilder.create().build(); 
  16.     } 
  17.  
  18.     @Bean(name = "postgresJdbcTemplate") 
  19.     public JdbcTemplate postgresJdbcTemplate(@Qualifier("postgresDb")  
  20.                                               DataSource dsPostgres) {        return new JdbcTemplate(dsPostgres); 
  21.     } 

解释:

这是加了注解的配置类,包含加载我们的PostgreSQL和MySQL数据库配置的函数和注解。这也会负责为每一种数据库创建JDBC模板类。

下面我们看一下这四个函数:

 
  1. @Bean(name = "mysqlDb")@ConfigurationProperties(prefix = "spring.ds_mysql")public DataSource mysqlDataSource() {return DataSourceBuilder.create().build(); 
  2. }  

上面代码第一行创建了mysqlDb bean。

第二行帮助@Bean加载了所有有前缀spring.ds_mysql的属性。

第四行创建并初始化了DataSource类,并创建了mysqlDb DataSource对象。

 
  1. @Bean(name = "mysqlJdbcTemplate")public JdbcTemplate jdbcTemplate(@Qualifier("mysqlDb") DataSource dsMySQL) {     return new JdbcTemplate(dsMySQL); 
  2. }  

第一行以mysqlJdbcTemplate为名创建了一个JdbcTemplate类型的新Bean。

第二行将第一行中创建的DataSource类型新参数传入函数,并以mysqlDB为qualifier。

第三行用DataSource对象初始化JdbcTemplate实例。

 
  1. @Bean(name = "postgresDb")@ConfigurationProperties(prefix = "spring.ds_post")public DataSource postgresDataSource() { return DataSourceBuilder.create().build(); 
  2.  
  3. }  

第一行创建DataSource实例postgresDb。

第二行帮助@Bean加载所有以spring.ds_post为前缀的配置。

第四行创建并初始化DataSource实例postgresDb。

 
  1. @Bean(name = "postgresJdbcTemplate")public JdbcTemplate postgresJdbcTemplate(@Qualifier("postgresDb") 
  2.  
  3. DataSource dsPostgres) { return new JdbcTemplate(dsPostgres); 
  4.  

第一行以postgresJdbcTemplate为名创建JdbcTemplate类型的新bean。

第二行接受DataSource类型的参数,并以postgresDb为qualifier。

第三行用DataSource对象初始化JdbcTemplate实例。

DemoController.java

 
  1. package com.aegis.controller;import java.util.HashMap;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController; 
  2.  
  3. @RestControllerpublic class DemoController { 
  4.  
  5.     @Autowired 
  6.     @Qualifier("postgresJdbcTemplate")    private JdbcTemplate postgresTemplate; 
  7.  
  8.     @Autowired 
  9.     @Qualifier("mysqlJdbcTemplate")    private JdbcTemplate mysqlTemplate; 
  10.  
  11.     @RequestMapping(value = "/getPGUser")    public String getPGUser() {        Map<String, Object> map = new HashMap<String, Object>();        String query = " select * from usermaster";        try {            map = postgresTemplate.queryForMap(query); 
  12.         } catch (Exception e) { 
  13.             e.printStackTrace(); 
  14.         }        return "PostgreSQL Data: " + map.toString(); 
  15.     } 
  16.  
  17.     @RequestMapping(value = "/getMYUser")    public String getMYUser() {        Map<String, Object> map = new HashMap<String, Object>();        String query = " select * from usermaster";        try {            map = mysqlTemplate.queryForMap(query); 
  18.         } catch (Exception e) { 
  19.             e.printStackTrace(); 
  20.         }        return "MySQL Data: " + map.toString(); 
  21.     } 

解释:

@RestController类注解表明这个类中定义的所有函数都被默认绑定到响应中。

上面代码段创建了一个JdbcTemplate实例。@Qualifier用于生成一个对应类型的模板。代码中提供的是postgresJdbcTemplate作为Qualifier参数,所以它会加载MultipleDBConfig实例的jdbcTemplate(…)函数创建的Bean。

这样Spring就会根据你的要求来调用合适的JDBC模板。在调用URL “/getPGUser”时Spring会用PostgreSQL模板,调用URL “/getMYUser”时Spring会用MySQL模板。

 
  1. @Autowired@Qualifier("postgresJdbcTemplate")private JdbcTemplate postgresTemplate; 

这里我们用queryForMap(String query)函数来使用JDBC模板从数据库中获取数据,queryForMap(…)返回一个map,以字段名为Key,Value为实际字段值。

演示

执行类MultipleDbApplication中的main (…)函数就可以看到演示效果。在你常用的浏览器中点击下面URL:

URL: http://localhost:6060/getMYUser

上面的URL会查询MySQL数据库并以字符串形式返回数据。

Url: http://localhost:6060/getPGUser

上面的URL会查询PostgreSQL数据库并以字符串形式返回数据。



作者:佚名

来源:51CTO

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
30天前
|
网络安全
ssh(Spring+Spring mvc+hibernate)——DeptDaoImpl.java
ssh(Spring+Spring mvc+hibernate)——DeptDaoImpl.java
11 0
|
30天前
|
网络安全
ssh(Spring+Spring mvc+hibernate)——BaseDaoImpl.java
ssh(Spring+Spring mvc+hibernate)——BaseDaoImpl.java
12 0
|
30天前
|
Shell
sh(Spring+Spring mvc+hibernate)——IEmpDao.java
sh(Spring+Spring mvc+hibernate)——IEmpDao.java
11 0
|
30天前
|
Shell
sh(Spring+Spring mvc+hibernate)——IDeptDao.java
sh(Spring+Spring mvc+hibernate)——IDeptDao.java
13 0
|
30天前
|
网络安全
ssh(Spring+Spring mvc+hibernate)——Dept.java
ssh(Spring+Spring mvc+hibernate)——Dept.java
11 0
|
1天前
|
Java 关系型数据库 MySQL
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
UWB (ULTRA WIDE BAND, UWB) 技术是一种无线载波通讯技术,它不采用正弦载波,而是利用纳秒级的非正弦波窄脉冲传输数据,因此其所占的频谱范围很宽。一套UWB精确定位系统,最高定位精度可达10cm,具有高精度,高动态,高容量,低功耗的应用。
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
|
3天前
|
负载均衡 Java 开发者
细解微服务架构实践:如何使用Spring Cloud进行Java微服务治理
【4月更文挑战第17天】Spring Cloud是Java微服务治理的首选框架,整合了Eureka(服务发现)、Ribbon(客户端负载均衡)、Hystrix(熔断器)、Zuul(API网关)和Config Server(配置中心)。通过Eureka实现服务注册与发现,Ribbon提供负载均衡,Hystrix实现熔断保护,Zuul作为API网关,Config Server集中管理配置。理解并运用Spring Cloud进行微服务治理是现代Java开发者的关键技能。
|
4天前
|
安全 Java 数据安全/隐私保护
使用Spring Security进行Java身份验证与授权
【4月更文挑战第16天】Spring Security是Java应用的安全框架,提供认证和授权解决方案。通过添加相关依赖到`pom.xml`,然后配置`SecurityConfig`,如设置用户认证信息和URL访问规则,可以实现应用的安全保护。认证流程包括请求拦截、身份验证、响应生成和访问控制。授权则涉及访问决策管理器,如基于角色的投票。Spring Security为开发者构建安全应用提供了全面且灵活的工具,涵盖OAuth2、CSRF保护等功能。
|
5天前
|
Java 大数据 云计算
Spring框架:Java后台开发的核心
【4月更文挑战第15天】Spring框架在Java后台开发中占据核心位置,因其控制反转(IoC)、面向切面编程(AOP)、事务管理等特性提升效率和质量。Spring提供数据访问集成、RESTful Web服务和WebSocket支持。优势包括高效开发、灵活扩展、强大生态圈和广泛应用。应用于企业级应用、微服务架构及云计算大数据场景。掌握Spring对Java开发者至关重要。
|
7天前
|
Java 应用服务中间件 Maven
使用IDEA搭建SpringMVC环境,Maven导入了依赖,但是运行报错 java.lang.ClassNotFoundException
使用IDEA搭建SpringMVC环境,Maven导入了依赖,但是运行报错 java.lang.ClassNotFoundException
8 1