1.创建两个数据库并创建book表格,表格中插入数据
-- ----------------------------
-- Table structure for book
-- ----------------------------
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
`name` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '名称',
`author` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '作者',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of book
-- ----------------------------
INSERT INTO `book` VALUES (1, '三国演义', '罗贯中');
INSERT INTO `book` VALUES (3, '西厢记', '王世普');
SET FOREIGN_KEY_CHECKS = 1;
2.引入依赖
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>jdbctemplate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jdbctemplate</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>8.0.11</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
注意这里添加的数据库连接池依赖是 druid spring-boot-starter, druid-spring-boot-starter 可以帮开发者在 Spring Boot 项目中轻松集成 Druid 数据库连接池和监控。
3.配置数据库连接注意这里一定要用apllication.propertoes文件如果用application.yml文件会报错,具体原因还未找到,如果有大佬知道原因,评论告知我,网上的解决方案我试了还是报错没法解决
server.port=8888
#数据源一
spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.one.username=root
spring.datasource.one.password=123
spring.datasource.one.url=jdbc:mysql://127.0.0.1:3306/master?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
#数据源二
spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.two.username=root
spring.datasource.two.password=123
spring.datasource.two.url=jdbc:mysql://127.0.0.1:3306/slave1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
4.配置数据源
package com.example.jdbctemplate.config;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
/**
* 配置数据源
* 提供了两个数据源: dsOne和dsTwo,默认方法名即实例名
* @ConfigurationProperties注解表示使用不同前缀的配置文件来创建不同的DataSorce实例
*/
@Configuration
public class DataSourceConfig {
/**
* 生成数据源一
* @return
*/
@Bean
@ConfigurationProperties("spring.datasource.one")
DataSource dsOne(){
return DruidDataSourceBuilder.create().build();
}
/**
* 生成数据源二
* @return
*/
@Bean
@ConfigurationProperties("spring.datasource.two")
DataSource dsTwo(){
return DruidDataSourceBuilder.create().build();
}
}
5.配置JdbcTemplate
package com.example.jdbctemplate.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
/**
* 配置JdbcTemplate
* JdbcTemplateConfig中提供了两个JdbcTemplate实例,每个JdbcTemplate实例都需要提供DataSource,
* 由于Spring容器中有两个DataSource实例,因此需要通过方法名查找。
* @Qualifier:表示查找不同名称的DataSource实例注入进来
*/
@Configuration
public class JdbcTemplateConfig {
/**
* 因为只要引入spring-jdbc依赖,name开发者没有提供JdbcTemplate实例时,SpringBoot默认会提供一个JdbcTemplate实例。
* 现在配置多数据源时,我们自己提供JdbcTemplate实例
* @param dataSource
* @return
*/
/**
* JdbcTemplate实例一
* @param dataSource
* @return
*/
@Bean
JdbcTemplate jdbcTemplateOne(@Qualifier("dsOne") DataSource dataSource){
return new JdbcTemplate(dataSource);
}
/**
* JdbcTemplate实例二
* @param dataSource
* @return
*/
@Bean
JdbcTemplate jdbcTemplateTwo(@Qualifier("dsTwo")DataSource dataSource){
return new JdbcTemplate(dataSource);
}
}
6.创建controller
package com.example.jdbctemplate.controller;
import com.example.jdbctemplate.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
* 在Controller中注入两个不同的JdbcTemplate有两种方式
* 方式一:一种是使用@Resource注解,并指明name属性,即按name进行装配,此时会根据实例名查找相应的实例注入
* 方式二:@Autowired注解结合@Qualifier注解,效果等同于使用@Resource注解
*/
@RestController
public class BookController {
@Resource(name ="jdbcTemplateOne")
JdbcTemplate jdbcTemplateOne;
@Autowired
@Qualifier("jdbcTemplateTwo")
JdbcTemplate jdbcTemplateTwo;
@GetMapping("/test1")
public void test1(){
List<Book> books1 = jdbcTemplateOne.query("select * from book",new BeanPropertyRowMapper<>(Book.class));
List<Book> books2 = jdbcTemplateTwo.query("select * from book",new BeanPropertyRowMapper<>(Book.class));
System.out.println("books1:" + books1);
System.out.println("books2:" + books2);
}
}
7.测试 http://localhost:8888/test1
2019-10-11 11:21:03.311 INFO 9268 --- [nio-8888-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-10-11 11:21:03.311 INFO 9268 --- [nio-8888-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-10-11 11:21:03.316 INFO 9268 --- [nio-8888-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 5 ms
2019-10-11 11:21:03.445 INFO 9268 --- [nio-8888-exec-1] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
2019-10-11 11:21:03.578 INFO 9268 --- [nio-8888-exec-1] com.alibaba.druid.pool.DruidDataSource : {dataSource-2} inited
books1:[Book{id=1, name='三国演义', author='罗贯中'}, Book{id=3, name='西厢记', author='王世普'}, Book{id=4, name='朝花夕拾', author='鲁迅'}, Book{id=5, name='西厢记', author='王世普'}, Book{id=6, name='西厢记', author='王世普'}, Book{id=7, name='西厢记', author='王世普'}]
books2:[Book{id=5, name='西厢记', author='王世普'}, Book{id=6, name='西厢记', author='王世普'}, Book{id=7, name='西厢记', author='王世普'}]
8.项目结构图