Java Spring中同時訪問多種不同數據庫
開發企業應用時我們常常遇到要同時訪問多種不同數據庫的問題,有時是必須把數據歸檔到某種數據倉庫中,有時是要把數據變更推送到第三方數據庫中。使用Spring框架時,使用單一數據庫是非常容易的,但如果要同時訪問多個數據庫的話事件就變得復雜多了。
本文以在Spring框架下開發一個SpringMVC程序為例,示范了一種同時訪問多種數據庫的方法,而且盡量地簡化配置改動。
搭建數據庫
建議你也同時搭好兩個數據庫來跟進我們的示例。本文中我們用了PostgreSQL和MySQL。
下面的腳本內容是在兩個數據庫中建表和插入數據的命令。
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');
搭建項目
我們用Spring Tool Suite (STS)來構建這個例子:
點擊File -> New -> Spring Starter Project。
在對話框中輸入項目名、Maven坐標、描述和包信息等,點擊Next。
在boot dependency中選擇Web,點擊Next。
點擊Finish。STS會自動按照項目依賴關系從Spring倉庫中下載所需要的內容。
創建完的項目如下圖所示:
接下來我們仔細研究一下項目中的各個相關文件內容。
pom.xml
pom中包含了所有需要的依賴和插件映射關系。
代碼:
- <?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>
解釋:
下面詳細解釋各種依賴關系的細節:
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文件來提供這些配置信息。
- 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”聲明你的嵌入式服務器啟動后會使用6060端口(port.server.port是Boot默認的標準端口)。
其他屬性中:
以“spring.ds_*”為前綴的是用戶定義屬性。
以“spring.ds_post.*”為前綴的是為PostgreSQL數據庫定義的屬性。
以“spring.ds_mysql.*”為前綴的是為MySQL數據庫定義的屬性。
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);
- }
- }
這個文件包含了啟動我們的Boot程序的主函數。注解“@SpringBootApplication”是所有其他Spring注解和Java注解的組合,包括:
- @Configuration@EnableAutoConfiguration@ComponentScan@Target(value={TYPE})@Retention(value=RUNTIME)@Documented@Inherited
其他注解:
- @Configuration@EnableAutoConfiguration@ComponentScan
上述注解會讓容器通過這個類來加載我們的配置。
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數據庫配置的函數和注解。這也會負責為每一種數據庫創建JDBC模板類。
下面我們看一下這四個函數:
- @Bean(name = "mysqlDb")@ConfigurationProperties(prefix = "spring.ds_mysql")public DataSource mysqlDataSource() {return DataSourceBuilder.create().build();
- }
上面代碼***行創建了mysqlDb bean。
第二行幫助@Bean加載了所有有前綴spring.ds_mysql的屬性。
第四行創建并初始化了DataSource類,并創建了mysqlDb DataSource對象。
- @Bean(name = "mysqlJdbcTemplate")public JdbcTemplate jdbcTemplate(@Qualifier("mysqlDb") DataSource dsMySQL) { return new JdbcTemplate(dsMySQL);
- }
***行以mysqlJdbcTemplate為名創建了一個JdbcTemplate類型的新Bean。
第二行將***行中創建的DataSource類型新參數傳入函數,并以mysqlDB為qualifier。
第三行用DataSource對象初始化JdbcTemplate實例。
- @Bean(name = "postgresDb")@ConfigurationProperties(prefix = "spring.ds_post")public DataSource postgresDataSource() { return DataSourceBuilder.create().build();
- }
***行創建DataSource實例postgresDb。
第二行幫助@Bean加載所有以spring.ds_post為前綴的配置。
第四行創建并初始化DataSource實例postgresDb。
- @Bean(name = "postgresJdbcTemplate")public JdbcTemplate postgresJdbcTemplate(@Qualifier("postgresDb")
- DataSource dsPostgres) { return new JdbcTemplate(dsPostgres);
- }
***行以postgresJdbcTemplate為名創建JdbcTemplate類型的新bean。
第二行接受DataSource類型的參數,并以postgresDb為qualifier。
第三行用DataSource對象初始化JdbcTemplate實例。
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類注解表明這個類中定義的所有函數都被默認綁定到響應中。
上面代碼段創建了一個JdbcTemplate實例。@Qualifier用于生成一個對應類型的模板。代碼中提供的是postgresJdbcTemplate作為Qualifier參數,所以它會加載MultipleDBConfig實例的jdbcTemplate(…)函數創建的Bean。
這樣Spring就會根據你的要求來調用合適的JDBC模板。在調用URL “/getPGUser”時Spring會用PostgreSQL模板,調用URL “/getMYUser”時Spring會用MySQL模板。
- @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數據庫并以字符串形式返回數據。
關于作者
Aaron Jacobson是個經驗豐富的Java Web程序員,在外包與咨詢公司Technoligent擔任Java開發程序員10年以上。他的主要貢獻包括Java、Python、Asp.Net和手機應用等一系列Web解決方案。可以通過Twitter @Techno_Ligent或Facebook @TechnoLigent聯系他。