springboot整合mybatis的多数据源解决办法
最近项目有一个非解决不可的问题,我们的项目中的用户表是用的自己库的数据,但是这些数据都是从一个已有库中迁过来的,所以用户信息都是在那个项目里面维护,自然而然我们项目不提供用户注册功能,这就有个问题,如何解决数据迁移的问题,总不能我每次都手动导数据吧,所以我决心写一个接口把那个库中的用户信息同步我们的库中去。
这又涉及到一个问题,如何在一个服务中连接两个库,在网上搜索了一番,算是把问题解决了,现将多数据源demo代码贴出来,先看一下我的目录结构
controller、mapper、pojo、service这几个常见的业务逻辑包我们放到最后看,先看一下util包里面的类
DatabaseType
/**
* 采用枚举的方法列出所有的数据源key(常用数据库名称来命名)
* 数据源个数和数据库个数保持一致
*/
public enum DatabaseType {
mytestdb,mytestdb2
}
这里就是列出所有的数据源,相当于定义了两个常量,便于统一维护
DynamicDataSource
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* 动态数据源(需要继承AbstractRoutingDataSource)
*/
public class DynamicDataSource extends AbstractRoutingDataSource { //定义一个线程安全的DatabaseType容器
private static final ThreadLocal<DatabaseType> contextHolder = new ThreadLocal<DatabaseType>(); public static DatabaseType getDatabaseType(){
return contextHolder.get();
} public static void setDatabaseType(DatabaseType type) {
contextHolder.set(type);
}
//获取当前线程的DatabaseType
protected Object determineCurrentLookupKey() {
return getDatabaseType();
}
}
在这里创建一个动态数据源的类,定义了DatabaseType的get和set方法,用getDatabaseType()获得一个当前线程的DatabaseType来重写determineCurrentLookupKey()方法。
最后来看一下config包下面的类
MybatisConfig
import java.util.HashMap;
import java.util.Map;
import java.util.Properties; import javax.sql.DataSource; import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.fiberhome.ms.multiDataSource.util.DatabaseType;
import com.fiberhome.ms.multiDataSource.util.DynamicDataSource; /**
* springboot集成mybatis的基本入口
* 1) 获取数据源
* 2)创建数据源
* 3)创建SqlSessionFactory
* 4)配置事务管理器,除非需要使用事务,否则不用配置
*/
@Configuration
public class MybatisConfig implements EnvironmentAware { private Environment environment; public void setEnvironment(final Environment environment) {
this.environment = environment;
} /**
* 创建数据源,从配置文件中获取数据源信息
*/
@Bean
public DataSource testDataSource() throws Exception {
Properties props = new Properties();
props.put("driverClassName", environment.getProperty("jdbc.driverClassName"));
props.put("url", environment.getProperty("jdbc.url"));
props.put("username", environment.getProperty("jdbc.username"));
props.put("password", environment.getProperty("jdbc.password"));
return DruidDataSourceFactory.createDataSource(props);
} @Bean
public DataSource test1DataSource() throws Exception {
Properties props = new Properties();
props.put("driverClassName", environment.getProperty("jdbc2.driverClassName"));
props.put("url", environment.getProperty("jdbc2.url"));
props.put("username", environment.getProperty("jdbc2.username"));
props.put("password", environment.getProperty("jdbc2.password"));
return DruidDataSourceFactory.createDataSource(props);
} /**注入数据源
*/
@Bean
public DynamicDataSource dataSource(@Qualifier("testDataSource")DataSource testDataSource, @Qualifier("test1DataSource")DataSource test1DataSource) {
Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
targetDataSources.put(DatabaseType.mytestdb, testDataSource);
targetDataSources.put(DatabaseType.mytestdb2, test1DataSource); DynamicDataSource dataSource = new DynamicDataSource();
dataSource.setTargetDataSources(targetDataSources);// 该方法是AbstractRoutingDataSource的方法
dataSource.setDefaultTargetDataSource(testDataSource);// 默认的datasource设置为myTestDbDataSource return dataSource;
} /**
* 根据数据源创建SqlSessionFactory
*/
@Bean
public SqlSessionFactory sqlSessionFactory(@Qualifier("testDataSource") DataSource testDataSource,
@Qualifier("test1DataSource") DataSource test1DataSource) throws Exception{
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
fb.setDataSource(this.dataSource(testDataSource, test1DataSource));
fb.setTypeAliasesPackage("com.fiberhome.ms.multiDataSource");// 指定基包
fb.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));//
return fb.getObject();
} /**
* 配置事务管理器
*/
@Bean
public DataSourceTransactionManager testTransactionManager(DynamicDataSource dataSource) throws Exception {
return new DataSourceTransactionManager(dataSource);
} }
上面这段代码在创建数据源DataSource实例时采用的是@bean注解注入的方式,使其成为受spring管理的bean。在后面的方法把两个DataSource作为参数传入,可以看到用了@Qualifier注解,加这个注解是为了解决多个实例无法直接装配的问题,在这里有两个DataSource类型的实例,需要指定名称装配。
还有数据源配置文件
application.properties
#the first datasource
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
jdbc.username = root
jdbc.password = 123456 #the second datasource
jdbc2.driverClassName = com.mysql.jdbc.Driver
jdbc2.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=UTF-8
jdbc2.username = root
jdbc2.password = 123456
说完了关键的通用代码,再来看看如何在业务代码中使用
UserServiceImpl
import com.fiberhome.ms.multiDataSource.mapper.UserMapper;
import com.fiberhome.ms.multiDataSource.pojo.User;
import com.fiberhome.ms.multiDataSource.service.UserService;
import com.fiberhome.ms.multiDataSource.util.DatabaseType;
import com.fiberhome.ms.multiDataSource.util.DynamicDataSource;
@Service
public class UserServiceImpl implements UserService { @Autowired
private UserMapper userMapper; @Override
public List<User> getTestUser() {
//设置数据源
DynamicDataSource.setDatabaseType(DatabaseType.mytestdb);
return userMapper.findUser();
} @Override
public List<User> getTest1User() {
//设置数据源
DynamicDataSource.setDatabaseType(DatabaseType.mytestdb2);
return userMapper.findUser();
} }
在service层的实现类中设置数据源即可指定哪个mapper接口使用哪个数据源,这样就OK了。剩下的业务代码很简单就不贴了。。。
springboot整合mybatis的多数据源解决办法的更多相关文章
- SpringBoot整合Mybatis之项目结构、数据源
已经有好些日子没有总结了,不是变懒了,而是我一直在奋力学习springboot的路上,现在也算是完成了第一阶段的学习,今天给各位总结总结. 之前在网上找过不少关于springboot的教程,都是一些比 ...
- SpringBoot系列七:SpringBoot 整合 MyBatis(配置 druid 数据源、配置 MyBatis、事务控制、druid 监控)
1.概念:SpringBoot 整合 MyBatis 2.背景 SpringBoot 得到最终效果是一个简化到极致的 WEB 开发,但是只要牵扯到 WEB 开发,就绝对不可能缺少数据层操作,所有的开发 ...
- SpringBoot整合Mybatis多数据源 (AOP+注解)
SpringBoot整合Mybatis多数据源 (AOP+注解) 1.pom.xml文件(开发用的JDK 10) <?xml version="1.0" encoding=& ...
- SpringBoot进阶教程 | 第四篇:整合Mybatis实现多数据源
这篇文章主要介绍,通过Spring Boot整合Mybatis后如何实现在一个工程中实现多数据源.同时可实现读写分离. 准备工作 环境: windows jdk 8 maven 3.0 IDEA 创建 ...
- springboot整合mybatis时无法读取xml文件解决方法(必读)
转 http://baijiahao.baidu.com/s?id=1588136004120071836&wfr=spider&for=pc 在springboot整合myba ...
- 三、SpringBoot 整合mybatis 多数据源以及分库分表
前言 说实话,这章本来不打算讲的,因为配置多数据源的网上有很多类似的教程.但是最近因为项目要用到分库分表,所以让我研究一下看怎么实现.我想着上一篇博客讲了多环境的配置,不同的环境调用不同的数据库,那接 ...
- 【springboot spring mybatis】看我怎么将springboot与spring整合mybatis与druid数据源
目录 概述 1.mybatis 2.druid 壹:spring整合 2.jdbc.properties 3.mybatis-config.xml 二:java代码 1.mapper 2.servic ...
- SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统实例
1.前言 本文主要介绍使用SpringBoot与shiro实现基于数据库的细粒度动态权限管理系统实例. 使用技术:SpringBoot.mybatis.shiro.thymeleaf.pagehelp ...
- SpringBoot整合MyBatisPlus配置动态数据源
目录 SpringBoot整合MyBatisPlus配置动态数据源 SpringBoot整合MyBatisPlus配置动态数据源 推文:2018开源中国最受欢迎的中国软件MyBatis-Plus My ...
随机推荐
- LeetCode专题-Python实现之第27题:Remove Element
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- Creating a ROS msg and srv
msg: msg files are simple text files that describe the fields of a ROS message. They are used to gen ...
- C# 在PPT幻灯片中创建图表
图表能够很直观的表现数据在某个时间段的变化趋势,或者呈现数据的整体和局部之间的相互关系,相较于大篇幅的文本数据,图表更增加了我们分析数据时选择的多样性,是我们挖掘数据背后潜在价值的一种更为有效地方式. ...
- C# 如何添加Excel页眉页脚(图片、文字、奇偶页不同)
简介 我们可以通过代码编程来对Excel工作表实现很多操作,在下面的示例中,将介绍如何来添加Excel页眉.页脚.在页眉处,我们可以添加文字,如公司名称.页码.工作表名.日期等,也可以添加图片,如LO ...
- Java的几道面试题目以及简短回答做个记录保存
最近没有继续用CSDN写博客了,转到博客园,什么时候自己搭建一个博客就好了. 一 谈谈你对Spring的工作原理的理解 引用一篇博客的讲解,https://www.cnblogs.com/xdp- ...
- 解决centos7.0安装mysql后出现access defind for user@'localhost'的错误
在使用yum 安装完mariadb, mariadb-server, mariadb-devel后 1. rpm -qa | grep maria 查看maria相关库的是否在进程中 2. net ...
- Vue2开发大全
参考资料: vuex element qs.js axios.js vue promise 关于ES6的Promise的使用深入理解 vue2 设置网页title的问题 Mint UI websto ...
- 总结:当静态路由和BGP同时存在时路由优选BGP的两种方法
结论: 方法一.配置BGP协议的外部优先级比静态路由的优先级高,优选BGP. 优点:配置简单. 缺点:全局生效,如果用户有针对某个静态路由想提高优先级,不受动态路由影响,则针对每个静态路由都需要人为提 ...
- 总结:web 发展的4个阶段
一.概述 随着人们的需求发展,web技术的发展也经历了多个阶段,下一个阶段总是伴随着解决上一阶段的问题,从静态文本.动态执行.动态自动生成文本,web应用,到web2.0,本文就详细描述这些阶段的特征 ...
- PJSIP 自动化测试工具安装 Python安装
Python安装,记录步骤如下 1.下载PythonIDE安装包 到官网 https://repo.continuum.io/archive/下载需要的版本,选择的Anaconda版本3的,当然也可以 ...