Java Spring中同時(shí)訪問多種不同數(shù)據(jù)庫
開發(fā)企業(yè)應(yīng)用時(shí)我們常常遇到要同時(shí)訪問多種不同數(shù)據(jù)庫的問題,有時(shí)是必須把數(shù)據(jù)歸檔到某種數(shù)據(jù)倉庫中,有時(shí)是要把數(shù)據(jù)變更推送到第三方數(shù)據(jù)庫中。使用Spring框架時(shí),使用單一數(shù)據(jù)庫是非常容易的,但如果要同時(shí)訪問多個(gè)數(shù)據(jù)庫的話事件就變得復(fù)雜多了。
本文以在Spring框架下開發(fā)一個(gè)SpringMVC程序?yàn)槔?,示范了一種同時(shí)訪問多種數(shù)據(jù)庫的方法,而且盡量地簡(jiǎn)化配置改動(dòng)。
搭建數(shù)據(jù)庫
建議你也同時(shí)搭好兩個(gè)數(shù)據(jù)庫來跟進(jìn)我們的示例。本文中我們用了PostgreSQL和MySQL。
下面的腳本內(nèi)容是在兩個(gè)數(shù)據(jù)庫中建表和插入數(shù)據(jù)的命令。
PostgreSQL
- CREATE TABLE usermaster (
- id integer,
- name character varying,
- emailid character varying,
- phoneno character varying(10),
- location character varying)
- INSERT INTO usermaster(id, name, emailid, phoneno, location)VALUES (1, 'name_postgres', 'email@email.com', '1234567890', 'IN');
MySQL
- CREATE TABLE `usermaster` ( `id` int(11) NOT NULL,
- `name` varchar(255) DEFAULT NULL,
- `emailid` varchar(20) DEFAULT NULL,
- `phoneno` varchar(20) DEFAULT NULL,
- `location` varchar(20) DEFAULT NULL,
- PRIMARY KEY (`id`)
- )INSERT INTO `kode12`.`usermaster`
- (`id`, `name`, `emailid`, `phoneno`, `location`)VALUES
- ('1', 'name_mysql', 'test@tset.com', '9876543210', 'IN');
搭建項(xiàng)目
我們用Spring Tool Suite (STS)來構(gòu)建這個(gè)例子:
點(diǎn)擊File -> New -> Spring Starter Project。
在對(duì)話框中輸入項(xiàng)目名、Maven坐標(biāo)、描述和包信息等,點(diǎn)擊Next。
在boot dependency中選擇Web,點(diǎn)擊Next。
點(diǎn)擊Finish。STS會(huì)自動(dòng)按照項(xiàng)目依賴關(guān)系從Spring倉庫中下載所需要的內(nèi)容。
創(chuàng)建完的項(xiàng)目如下圖所示:
接下來我們仔細(xì)研究一下項(xiàng)目中的各個(gè)相關(guān)文件內(nèi)容。
pom.xml
pom中包含了所有需要的依賴和插件映射關(guān)系。
代碼:
- <?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
- http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.aegis</groupId>
- <artifactId>MultipleDBConnect</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
- <name>MultipleDB</name>
- <description>MultipleDB with Spring Boot</description>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>1.3.5.RELEASE</version>
- <relativePath />
- </parent>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <java.version>1.8</java.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <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-jdbc</artifactId>
- </dependency>
- <dependency>
- <groupId>org.postgresql</groupId>
- <artifactId>postgresql</artifactId>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.38</version>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build></project>
解釋:
下面詳細(xì)解釋各種依賴關(guān)系的細(xì)節(jié):
spring-boot-starter-web:為Web開發(fā)和MVC提供支持。
spring-boot-starter-test:提供JUnit、Mockito等測(cè)試依賴。
spring-boot-starter-jdbc:提供JDBC支持。
postgresql:PostgreSQL數(shù)據(jù)庫的JDBC驅(qū)動(dòng)。
mysql-connector-java:MySQL數(shù)據(jù)庫的JDBC驅(qū)動(dòng)。
application.properties
包含程序需要的所有配置信息。在舊版的Spring中我們要通過多個(gè)XML文件來提供這些配置信息。
- server.port=6060spring.ds_post.url =jdbc:postgresql://localhost:5432/kode12spring.ds_post.username =postgres
- spring.ds_post.password =root
- spring.ds_post.driverClassName=org.postgresql.Driverspring.ds_mysql.url = jdbc:mysql://localhost:3306/kode12spring.ds_mysql.username = root
- spring.ds_mysql.password = root
- spring.ds_mysql.driverClassName=com.mysql.jdbc.Driver
解釋:
“server.port=6060”聲明你的嵌入式服務(wù)器啟動(dòng)后會(huì)使用6060端口(port.server.port是Boot默認(rèn)的標(biāo)準(zhǔn)端口)。
其他屬性中:
以“spring.ds_*”為前綴的是用戶定義屬性。
以“spring.ds_post.*”為前綴的是為PostgreSQL數(shù)據(jù)庫定義的屬性。
以“spring.ds_mysql.*”為前綴的是為MySQL數(shù)據(jù)庫定義的屬性。
MultipleDbApplication.java
- package com.aegis;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic MultipleDbApplication { public static void main(String[] args) {
- SpringApplication.run(MultipleDbApplication.class, args);
- }
- }
這個(gè)文件包含了啟動(dòng)我們的Boot程序的主函數(shù)。注解“@SpringBootApplication”是所有其他Spring注解和Java注解的組合,包括:
- @Configuration@EnableAutoConfiguration@ComponentScan@Target(value={TYPE})@Retention(value=RUNTIME)@Documented@Inherited
其他注解:
- @Configuration@EnableAutoConfiguration@ComponentScan
上述注解會(huì)讓容器通過這個(gè)類來加載我們的配置。
MultipleDBConfig.java
- 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;
- @Configurationpublic class MultipleDBConfig {
- @Bean(name = "mysqlDb")
- @ConfigurationProperties(prefix = "spring.ds_mysql")
- public DataSource mysqlDataSource() { return DataSourceBuilder.create().build();
- }
- @Bean(name = "mysqlJdbcTemplate")
- public JdbcTemplate jdbcTemplate(@Qualifier("mysqlDb") DataSource dsMySQL) { return new JdbcTemplate(dsMySQL);
- }
- @Bean(name = "postgresDb")
- @ConfigurationProperties(prefix = "spring.ds_post")
- public DataSource postgresDataSource() { return DataSourceBuilder.create().build();
- }
- @Bean(name = "postgresJdbcTemplate")
- public JdbcTemplate postgresJdbcTemplate(@Qualifier("postgresDb")
- DataSource dsPostgres) { return new JdbcTemplate(dsPostgres);
- }
- }
解釋:
這是加了注解的配置類,包含加載我們的PostgreSQL和MySQL數(shù)據(jù)庫配置的函數(shù)和注解。這也會(huì)負(fù)責(zé)為每一種數(shù)據(jù)庫創(chuàng)建JDBC模板類。
下面我們看一下這四個(gè)函數(shù):
- @Bean(name = "mysqlDb")@ConfigurationProperties(prefix = "spring.ds_mysql")public DataSource mysqlDataSource() {return DataSourceBuilder.create().build();
- }
上面代碼***行創(chuàng)建了mysqlDb bean。
第二行幫助@Bean加載了所有有前綴spring.ds_mysql的屬性。
第四行創(chuàng)建并初始化了DataSource類,并創(chuàng)建了mysqlDb DataSource對(duì)象。
- @Bean(name = "mysqlJdbcTemplate")public JdbcTemplate jdbcTemplate(@Qualifier("mysqlDb") DataSource dsMySQL) { return new JdbcTemplate(dsMySQL);
- }
***行以mysqlJdbcTemplate為名創(chuàng)建了一個(gè)JdbcTemplate類型的新Bean。
第二行將***行中創(chuàng)建的DataSource類型新參數(shù)傳入函數(shù),并以mysqlDB為qualifier。
第三行用DataSource對(duì)象初始化JdbcTemplate實(shí)例。
- @Bean(name = "postgresDb")@ConfigurationProperties(prefix = "spring.ds_post")public DataSource postgresDataSource() { return DataSourceBuilder.create().build();
- }
***行創(chuàng)建DataSource實(shí)例postgresDb。
第二行幫助@Bean加載所有以spring.ds_post為前綴的配置。
第四行創(chuàng)建并初始化DataSource實(shí)例postgresDb。
- @Bean(name = "postgresJdbcTemplate")public JdbcTemplate postgresJdbcTemplate(@Qualifier("postgresDb")
- DataSource dsPostgres) { return new JdbcTemplate(dsPostgres);
- }
***行以postgresJdbcTemplate為名創(chuàng)建JdbcTemplate類型的新bean。
第二行接受DataSource類型的參數(shù),并以postgresDb為qualifier。
第三行用DataSource對(duì)象初始化JdbcTemplate實(shí)例。
DemoController.java
- 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;
- @RestControllerpublic class DemoController {
- @Autowired
- @Qualifier("postgresJdbcTemplate") private JdbcTemplate postgresTemplate;
- @Autowired
- @Qualifier("mysqlJdbcTemplate") private JdbcTemplate mysqlTemplate;
- @RequestMapping(value = "/getPGUser") public String getPGUser() { Map<String, Object> map = new HashMap<String, Object>(); String query = " select * from usermaster"; try { map = postgresTemplate.queryForMap(query);
- } catch (Exception e) {
- e.printStackTrace();
- } return "PostgreSQL Data: " + map.toString();
- }
- @RequestMapping(value = "/getMYUser") public String getMYUser() { Map<String, Object> map = new HashMap<String, Object>(); String query = " select * from usermaster"; try { map = mysqlTemplate.queryForMap(query);
- } catch (Exception e) {
- e.printStackTrace();
- } return "MySQL Data: " + map.toString();
- }
- }
解釋:
@RestController類注解表明這個(gè)類中定義的所有函數(shù)都被默認(rèn)綁定到響應(yīng)中。
上面代碼段創(chuàng)建了一個(gè)JdbcTemplate實(shí)例。@Qualifier用于生成一個(gè)對(duì)應(yīng)類型的模板。代碼中提供的是postgresJdbcTemplate作為Qualifier參數(shù),所以它會(huì)加載MultipleDBConfig實(shí)例的jdbcTemplate(…)函數(shù)創(chuàng)建的Bean。
這樣Spring就會(huì)根據(jù)你的要求來調(diào)用合適的JDBC模板。在調(diào)用URL “/getPGUser”時(shí)Spring會(huì)用PostgreSQL模板,調(diào)用URL “/getMYUser”時(shí)Spring會(huì)用MySQL模板。
- @Autowired@Qualifier("postgresJdbcTemplate")private JdbcTemplate postgresTemplate;
這里我們用queryForMap(String query)函數(shù)來使用JDBC模板從數(shù)據(jù)庫中獲取數(shù)據(jù),queryForMap(…)返回一個(gè)map,以字段名為Key,Value為實(shí)際字段值。
演示
執(zhí)行類MultipleDbApplication中的main (…)函數(shù)就可以看到演示效果。在你常用的瀏覽器中點(diǎn)擊下面URL:
URL: http://localhost:6060/getMYUser
上面的URL會(huì)查詢MySQL數(shù)據(jù)庫并以字符串形式返回?cái)?shù)據(jù)。
Url: http://localhost:6060/getPGUser
上面的URL會(huì)查詢PostgreSQL數(shù)據(jù)庫并以字符串形式返回?cái)?shù)據(jù)。
關(guān)于作者
Aaron Jacobson是個(gè)經(jīng)驗(yàn)豐富的Java Web程序員,在外包與咨詢公司Technoligent擔(dān)任Java開發(fā)程序員10年以上。他的主要貢獻(xiàn)包括Java、Python、Asp.Net和手機(jī)應(yīng)用等一系列Web解決方案??梢酝ㄟ^Twitter @Techno_Ligent或Facebook @TechnoLigent聯(lián)系他。