使用SpringBoot配置多数据源的经验分享
作者:码拉松 发布时间:2022-05-25 04:02:57
标签:SpringBoot,多数据源
1. 引入jar包
pom.xml文件
<?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.5.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.multi.datasource</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</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</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.22</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
2. properties配置
分别准备两个数据源
server.port=18888
mybatis.mapper-locations=classpath:mapper/*.xml
my1.datasource.url=jdbc:mysql://10.0.0.125:3306/wyl?autoReconnect=true
my1.datasource.driverClassName=com.mysql.cj.jdbc.Driver
my1.datasource.username=root
my1.datasource.password=123456
my2.datasource.url=jdbc:mysql://10.0.0.160:3306/wyl?autoReconnect=true
my2.datasource.driverClassName=com.mysql.cj.jdbc.Driver
my2.datasource.username=root
my2.datasource.password=123456
3. 分别配置两个数据源
第一个数据源
package com.multi.datasource.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = My1DataSourceConfig.PACKAGE, sqlSessionFactoryRef = "my1SqlSessionFactory")
public class My1DataSourceConfig {
static final String PACKAGE = "com.multi.datasource.dao.my1";
static final String MAPPER_LOCATION = "classpath:mapper/*.xml";
@Value("${my1.datasource.url}")
private String url;
@Value("${my1.datasource.username}")
private String user;
@Value("${my1.datasource.password}")
private String password;
@Value("${my1.datasource.driverClassName}")
private String driverClass;
@Bean(name = "my1DataSource")
public DataSource my1DataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
dataSource.setMaxWait(Integer.MAX_VALUE);
dataSource.setTestOnBorrow(true);
dataSource.setTestOnReturn(true);
dataSource.setTestWhileIdle(true);
return dataSource;
}
@Bean(name = "my1TransactionManager")
public DataSourceTransactionManager my1TransactionManager() {
return new DataSourceTransactionManager(my1DataSource());
}
@Bean(name = "my1SqlSessionFactory")
public SqlSessionFactory my1SqlSessionFactory(@Qualifier("my1DataSource") DataSource my1DataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(my1DataSource);
sessionFactory.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources(My1DataSourceConfig.MAPPER_LOCATION));
return sessionFactory.getObject();
}
}
第二个数据源
package com.multi.datasource.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = My1DataSourceConfig.PACKAGE, sqlSessionFactoryRef = "my1SqlSessionFactory")
public class My1DataSourceConfig {
static final String PACKAGE = "com.multi.datasource.dao.my1";
static final String MAPPER_LOCATION = "classpath:mapper/*.xml";
@Value("${my1.datasource.url}")
private String url;
@Value("${my1.datasource.username}")
private String user;
@Value("${my1.datasource.password}")
private String password;
@Value("${my1.datasource.driverClassName}")
private String driverClass;
@Bean(name = "my1DataSource")
public DataSource my1DataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
dataSource.setMaxWait(Integer.MAX_VALUE);
dataSource.setTestOnBorrow(true);
dataSource.setTestOnReturn(true);
dataSource.setTestWhileIdle(true);
return dataSource;
}
@Bean(name = "my1TransactionManager")
public DataSourceTransactionManager my1TransactionManager() {
return new DataSourceTransactionManager(my1DataSource());
}
@Bean(name = "my1SqlSessionFactory")
public SqlSessionFactory my1SqlSessionFactory(@Qualifier("my1DataSource") DataSource my1DataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(my1DataSource);
sessionFactory.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources(My1DataSourceConfig.MAPPER_LOCATION));
return sessionFactory.getObject();
}
}
4. Dao目录
为了区分两个数据源,分别设置了不同的目录
package com.multi.datasource.dao.my1;
import com.multi.datasource.entity.UserEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface Test1Mapper {
UserEntity query();
}
package com.multi.datasource.dao.my2;
import com.multi.datasource.entity.UserEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface Test2Mapper {
UserEntity query();
}
5. Entity
package com.multi.datasource.entity;
import lombok.Data;
@Data
public class UserEntity {
private String userName;
}
6. Mapper文件
从my1数据源查询
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.multi.datasource.dao.my1.Test1Mapper">
<select id="query" resultType="com.multi.datasource.entity.UserEntity">
select user_name as userName from t_user
</select>
</mapper>
从my2数据源查询
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.multi.datasource.dao.my2.Test2Mapper">
<select id="query" resultType="com.multi.datasource.entity.UserEntity">
select user_name as userName from t_user
</select>
</mapper>
7. Controller测试
package com.multi.datasource.controller;
import com.multi.datasource.dao.my1.Test1Mapper;
import com.multi.datasource.dao.my2.Test2Mapper;
import com.multi.datasource.entity.UserEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
public class TestController {
@Resource
private Test1Mapper test1Mapper;
@Resource
private Test2Mapper test2Mapper;
@RequestMapping("query")
public void query() {
UserEntity user1 = test1Mapper.query();
System.out.println("my1 dataSource:" + user1);
UserEntity user2 = test2Mapper.query();
System.out.println("my2 dataSource:" + user2);
}
}
两个数据源,对应的user_name
分别是zhangsan和lisi
8. 结果验证
访问 http://localhost:18888/query
,结果如下
来源:https://blog.csdn.net/CSDN_WYL2016/article/details/124086758


猜你喜欢
- mapper.xml中if标签test判断的用法1. 字符串等于条件的两种写法① 将双引号和单引号的位置互换<if test='
- List接口介绍—ArrayList有序、可重复线程不安全,因为没有synchronized修饰ArrayList源码结论ArrayList
- 用DataFormatString格式化GridView在 GridView里面显示数据,要显示的数据有好多位小数,就想让它只显示两位小数,
- 本文实例讲述了java实现的RSA加密算法。分享给大家供大家参考,具体如下:一、什么是非对称加密1、加密的密钥与加密的密钥不相同,这样的加密
- 循环依赖定义循环依赖就 循环引用,就是两个或多个 bean 相互之间的持有对方,比如 CircleA 引用 CircleB , Circle
- 配置准备在build.gradle文件中添加如下依赖: compile "org.elasticsearc
- .NET包含一个特殊的Object类,可以接受任意的数据类型的值,当所传递或所赋值的类型不是一个特定的数据类型时,object类就提供了一种
- 本文实例讲述了Android编程使用pull方式解析xml格式文件的方法。分享给大家供大家参考,具体如下:上次已经说过使用Android s
- 写在前面之前想尝试把JWT和Shiro结合到一起,但是在网上查了些博客,也没太有看懂,所以就自己重新研究了一下Shiro的工作机制,然后自己
- 场景描述单例模式对于我们来说一点也不模式,是一个常见的名称,单例模式在程序中的实际效果就是:确保一个程序中只有一个实例,并提供一个全局访问点
- 初识LinkedHashMap大多数情况下,只要不涉及线程安全问题,Map基本都可以使用HashMap,不过HashMap有一个问题,就是迭
- 一、月份英文简写DateTime dt = DateTime.Now;string MM = dt.AddMonths(-1).ToStri
- 前言本文主要介绍了关于android实现一键锁屏和一键卸载的相关内容,分享出来供大家参考学习,这两个功能也是大家在开发中会遇到的两个需求,下
- 一、日志的分类1、名字分类log4j :log for java (因为for和4读音差不多,所以交log4j)logBack 日志说明注意
- 近日有朋友问我有没有如下图效果的开源控件相信大家无论是用IOS还是Android,都对这种效果不陌生,很多主流APP都会有这样或类似的效果,
- Java生态圈中有很多处理JSON和XML格式化的类库,Jackson是其中比较著名的一个。虽然JDK自带了XML处理类库,但是相对来说比较
- 在windows环境下,我们通常在IDE如VS的工程中开发C++项目,对于生成和使用静态库(*.lib)与动态库(*.dll)可能都已经比较
- 对于之前最火的无外乎集五福了,而五福除了加十个好友获得外,最直接的途径就是支付宝的咻一咻了。那么咻一咻具体有哪些实现方式呢?下面我们将一一介
- FloatingActionButton项目在github上的主页:https://github.com/futuresimple/andr
- 一、前言1、简单的登录验证可以通过Session或者Cookie实现。2、每次登录的时候都要进数据库校验下账户名和密码,只是加了cookie