SpringBoot2+Mybatis两个数据源实现 (二)

2024-04-05 07:18

本文主要是介绍SpringBoot2+Mybatis两个数据源实现 (二),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

之前转过一篇《SpringBoot2+Mybatis多个数据源实现》,今天补充一个其他的解决方案(原理差不多),这里是使用mysql+sqlserver作为数据源,可以供大家参考一下。

一、依赖引入

首先引入必要的jar包,有省略,自行补充
pom.xml

<!--连接池 -->
<dependency><groupId>com.zaxxer</groupId><artifactId>HikariCP</artifactId><version>3.2.0</version>
</dependency>
<!--mysql -->
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.31</version>
</dependency>
<!-- sqlserver-->
<dependency><groupId>com.microsoft.sqlserver</groupId><artifactId>sqljdbc4</artifactId><version>4.0</version>
</dependency>
<!-- mybatis -->
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.0.0</version>
</dependency>
二、代码实现

先创建 DatabaseType,定义两个数据源的名称

public enum DatabaseType {mysqlDataSource,sqlServerDataSource
}

实现DatabaseContextHolder

public class DatabaseContextHolder {private static final ThreadLocal<DatabaseType> contextHolder = new ThreadLocal<>();public static void setDatabaseType(DatabaseType type) {contextHolder.set(type);}public static DatabaseType getDatabaseType() {return contextHolder.get();}
}

实现DynamicDataSource

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;public class DynamicDataSource extends AbstractRoutingDataSource {@Overrideprotected Object determineCurrentLookupKey() {return DatabaseContextHolder.getDatabaseType();}
}

实现MyBatisConfig

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
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 javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;@Configuration // 该注解类似于spring配置文件
@MapperScan(basePackages = "com.xxx.dao")
public class MyBatisConfig {@Autowiredprivate Environment env;// 读取主数据源@Beanpublic DataSource mysqlDataSource(Environment env) {Map<String, Object> dsMap = new HashMap<>();dsMap.put("type", env.getProperty("spring.datasource.type"));dsMap.put("driver", env.getProperty("spring.datasource.driver-class-name"));dsMap.put("url", env.getProperty("spring.datasource.url"));dsMap.put("username", env.getProperty("spring.datasource.username"));dsMap.put("password", env.getProperty("spring.datasource.password"));return buildDataSource(dsMap);}// 读取从数据源@Beanpublic DataSource sqlServerDataSource(Environment env) {Map<String, Object> dsMap = new HashMap<>();dsMap.put("type", env.getProperty("slave.datasource.type"));dsMap.put("driver", env.getProperty("slave.datasource.driver-class-name"));dsMap.put("url", env.getProperty("slave.datasource.url"));dsMap.put("username", env.getProperty("slave.datasource.username"));dsMap.put("password", env.getProperty("slave.datasource.password"));return buildDataSource(dsMap);}/*** @Primary 该注解表示在同一个接口有多个实现类可以注入的时候,默认选择哪一个,而不是让@autowire注解报错* @Qualifier 根据名称进行注入,通常是在具有相同的多个类型的实例的一个注入(例如有多个DataSource类型的实例)*/@Bean@Primarypublic DynamicDataSource dataSource(@Qualifier("mysqlDataSource") DataSource mysqlDataSource,@Qualifier("sqlServerDataSource") DataSource sqlServerDataSource) {Map<Object, Object> targetDataSources = new HashMap<>();targetDataSources.put(DatabaseType.mysqlDataSource, mysqlDataSource);targetDataSources.put(DatabaseType.sqlServerDataSource, sqlServerDataSource);DynamicDataSource dataSource = new DynamicDataSource();dataSource.setTargetDataSources(targetDataSources);// 该方法是AbstractRoutingDataSource的方法dataSource.setDefaultTargetDataSource(mysqlDataSource);// 默认的datasource设return dataSource;}/*** 根据数据源创建SqlSessionFactory*/@Beanpublic SqlSessionFactory sqlSessionFactory(DynamicDataSource ds) throws Exception {SqlSessionFactoryBean fb = new SqlSessionFactoryBean();fb.setDataSource(ds);// 指定数据源(这个必须有,否则报错)// 下边两句仅仅用于*.xml文件,如果整个持久层操作不需要使用到xml文件的话(只用注解就可以搞定),则不加//fb.setTypeAliasesPackage(env.getProperty("mybatis.typeAliasesPackage"));// 指定基包fb.setConfigLocation(new PathMatchingResourcePatternResolver().getResource(env.getProperty("mybatis.config-location")));fb.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(env.getProperty("mybatis.mapper-locations")));return fb.getObject();}/*** 配置事务管理器*/@Beanpublic DataSourceTransactionManager transactionManager(DynamicDataSource dataSource) throws Exception {return new DataSourceTransactionManager(dataSource);}/*** 创建DataSource* @param dataSourceMap* @return*/public DataSource buildDataSource(Map<String, Object> dataSourceMap) {try {Object type = dataSourceMap.get("type");Class<? extends DataSource> dataSourceType = (Class<? extends DataSource>) Class.forName((String) type);String driverClassName = dataSourceMap.get("driver").toString();String url = dataSourceMap.get("url").toString();String username = dataSourceMap.get("username").toString();String password = dataSourceMap.get("password").toString();// 自定义DataSource配置DataSourceBuilder factory = DataSourceBuilder.create().driverClassName(driverClassName).url(url).username(username).password(password).type(dataSourceType);return factory.build();} catch (ClassNotFoundException e) {e.printStackTrace();}return null;}
}
三、yml文件配置

application.yml

server:tomcat:uri-encoding: UTF-8max-threads: 1000min-spare-threads: 30port: 8888spring:profiles:active: dev#mybatis
mybatis:mapper-locations: classpath:mybatis/mappers/*.xmlconfig-location: classpath:mybatis/mybatis-config.xml

定义application-dev.yml

#mysql
spring:datasource:driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://127.0.0.1:33306/test1?useAffectedRows=true&characterEncoding=utf8username: rootpassword: roottype: com.zaxxer.hikari.HikariDataSourcehikari:connection-timeout: 30000idle-timeout: 600000max-lifetime: 1800000maximum-pool-size: 10#sqlserver
slave:datasource:driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriverurl: jdbc:sqlserver://127.0.0.1:1433;DatabaseName=test2;username: sapassword: 123456type: com.zaxxer.hikari.HikariDataSourcehikari:connection-timeout: 30000idle-timeout: 600000max-lifetime: 1800000maximum-pool-size: 10
四、使用方式

建议在service实现类里面使用

public List<Demo> queryList(){//切换数据源DatabaseContextHolder.setDatabaseType(DatabaseType.sqlServerDataSource);Map<String,Object> map = new HashMap<>();return demoDao.queryList(map);
}public List<Demo> selectList(){//切换数据源DatabaseContextHolder.setDatabaseType(DatabaseType.mysqlDataSource);Map<String,Object> map = new HashMap<>();return demoDao.queryList(map);
}

20190709更新
之前hikari的配置未生效

hikari:connection-timeout: 30000idle-timeout: 600000max-lifetime: 1800000maximum-pool-size: 10

今天优化了一下MyBatisConfig,增加了配置Hikari dataSource的超时设置,详细看代码

package com.xxx.config;import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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 javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;@Configuration // 该注解类似于spring配置文件
@MapperScan(basePackages = "com.xxx.dao")
public class MyBatisConfig {@Autowiredprivate Environment env;// 读取主数据源@Beanpublic DataSource mysqlDataSource(Environment env) {HikariConfig config = new HikariConfig();config.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));config.setJdbcUrl(env.getProperty("spring.datasource.url"));config.setUsername(env.getProperty("spring.datasource.username"));config.setPassword(env.getProperty("spring.datasource.password"));config.setConnectionTestQuery(env.getProperty("spring.datasource.ConnectionTestQuery"));config.setMaximumPoolSize(Integer.parseInt(env.getProperty("spring.datasource.hikari.maximum-pool-size")));config.setIdleTimeout(Integer.parseInt(env.getProperty("spring.datasource.hikari.idle-timeout")));config.setMaxLifetime(Integer.parseInt(env.getProperty("spring.datasource.hikari.max-lifetime")));config.setConnectionTimeout(Integer.parseInt(env.getProperty("spring.datasource.hikari.connection-timeout")));DataSource dataSource = new HikariDataSource(config);return dataSource;}// 读取从数据源@Beanpublic DataSource sqlServerDataSource(Environment env) {HikariConfig config = new HikariConfig();config.setDriverClassName(env.getProperty("slave.datasource.driver-class-name"));config.setJdbcUrl(env.getProperty("slave.datasource.url"));config.setUsername(env.getProperty("slave.datasource.username"));config.setPassword(env.getProperty("slave.datasource.password"));config.setConnectionTestQuery(env.getProperty("slave.datasource.ConnectionTestQuery"));config.setMaximumPoolSize(Integer.parseInt(env.getProperty("slave.datasource.hikari.maximum-pool-size")));config.setIdleTimeout(Integer.parseInt(env.getProperty("slave.datasource.hikari.idle-timeout")));config.setMaxLifetime(Integer.parseInt(env.getProperty("slave.datasource.hikari.max-lifetime")));config.setConnectionTimeout(Integer.parseInt(env.getProperty("slave.datasource.hikari.connection-timeout")));DataSource dataSource = new HikariDataSource(config);return dataSource;}/*** @Primary 该注解表示在同一个接口有多个实现类可以注入的时候,默认选择哪一个,而不是让@autowire注解报错* @Qualifier 根据名称进行注入,通常是在具有相同的多个类型的实例的一个注入(例如有多个DataSource类型的实例)*/@Bean@Primarypublic DynamicDataSource dataSource(@Qualifier("mysqlDataSource") DataSource mysqlDataSource,@Qualifier("sqlServerDataSource") DataSource sqlServerDataSource) {Map<Object, Object> targetDataSources = new HashMap<>();targetDataSources.put(DatabaseType.mysqlDataSource, mysqlDataSource);targetDataSources.put(DatabaseType.sqlServerDataSource, sqlServerDataSource);DynamicDataSource dataSource = new DynamicDataSource();dataSource.setTargetDataSources(targetDataSources);// 该方法是AbstractRoutingDataSource的方法dataSource.setDefaultTargetDataSource(mysqlDataSource);// 默认的datasource设return dataSource;}/*** 根据数据源创建SqlSessionFactory*/@Beanpublic SqlSessionFactory sqlSessionFactory(DynamicDataSource ds) throws Exception {SqlSessionFactoryBean fb = new SqlSessionFactoryBean();fb.setDataSource(ds);// 指定数据源(这个必须有,否则报错)// 下边两句仅仅用于*.xml文件,如果整个持久层操作不需要使用到xml文件的话(只用注解就可以搞定),则不加//fb.setTypeAliasesPackage(env.getProperty("mybatis.typeAliasesPackage"));// 指定基包fb.setConfigLocation(new PathMatchingResourcePatternResolver().getResource(env.getProperty("mybatis.config-location")));fb.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(env.getProperty("mybatis.mapper-locations")));//return fb.getObject();}/*** 配置事务管理器*/@Beanpublic DataSourceTransactionManager transactionManager(DynamicDataSource dataSource) throws Exception {return new DataSourceTransactionManager(dataSource);}
}

这篇关于SpringBoot2+Mybatis两个数据源实现 (二)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/877958

相关文章

Python3脚本实现Excel与TXT的智能转换

《Python3脚本实现Excel与TXT的智能转换》在数据处理的日常工作中,我们经常需要将Excel中的结构化数据转换为其他格式,本文将使用Python3实现Excel与TXT的智能转换,需要的可以... 目录场景应用:为什么需要这种转换技术解析:代码实现详解核心代码展示改进点说明实战演练:从Excel到

如何使用CSS3实现波浪式图片墙

《如何使用CSS3实现波浪式图片墙》:本文主要介绍了如何使用CSS3的transform属性和动画技巧实现波浪式图片墙,通过设置图片的垂直偏移量,并使用动画使其周期性地改变位置,可以创建出动态且具有波浪效果的图片墙,同时,还强调了响应式设计的重要性,以确保图片墙在不同设备上都能良好显示,详细内容请阅读本文,希望能对你有所帮助...

Spring Boot 3 整合 Spring Cloud Gateway实践过程

《SpringBoot3整合SpringCloudGateway实践过程》本文介绍了如何使用SpringCloudAlibaba2023.0.0.0版本构建一个微服务网关,包括统一路由、限... 目录引子为什么需要微服务网关实践1.统一路由2.限流防刷3.登录鉴权小结引子当前微服务架构已成为中大型系统的标

C# string转unicode字符的实现

《C#string转unicode字符的实现》本文主要介绍了C#string转unicode字符的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随... 目录1. 获取字符串中每个字符的 Unicode 值示例代码:输出:2. 将 Unicode 值格式化

python安装whl包并解决依赖关系的实现

《python安装whl包并解决依赖关系的实现》本文主要介绍了python安装whl包并解决依赖关系的实现,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录一、什么是whl文件?二、我们为什么需要使用whl文件来安装python库?三、我们应该去哪儿下

Python脚本实现图片文件批量命名

《Python脚本实现图片文件批量命名》这篇文章主要为大家详细介绍了一个用python第三方库pillow写的批量处理图片命名的脚本,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录前言源码批量处理图片尺寸脚本源码GUI界面源码打包成.exe可执行文件前言本文介绍一个用python第三方库pi

Java中将异步调用转为同步的五种实现方法

《Java中将异步调用转为同步的五种实现方法》本文介绍了将异步调用转为同步阻塞模式的五种方法:wait/notify、ReentrantLock+Condition、Future、CountDownL... 目录异步与同步的核心区别方法一:使用wait/notify + synchronized代码示例关键

Nginx实现动态封禁IP的步骤指南

《Nginx实现动态封禁IP的步骤指南》在日常的生产环境中,网站可能会遭遇恶意请求、DDoS攻击或其他有害的访问行为,为了应对这些情况,动态封禁IP是一项十分重要的安全策略,本篇博客将介绍如何通过NG... 目录1、简述2、实现方式3、使用 fail2ban 动态封禁3.1 安装 fail2ban3.2 配

Java中实现订单超时自动取消功能(最新推荐)

《Java中实现订单超时自动取消功能(最新推荐)》本文介绍了Java中实现订单超时自动取消功能的几种方法,包括定时任务、JDK延迟队列、Redis过期监听、Redisson分布式延迟队列、Rocket... 目录1、定时任务2、JDK延迟队列 DelayQueue(1)定义实现Delayed接口的实体类 (

springboot的调度服务与异步服务使用详解

《springboot的调度服务与异步服务使用详解》本文主要介绍了Java的ScheduledExecutorService接口和SpringBoot中如何使用调度线程池,包括核心参数、创建方式、自定... 目录1.调度服务1.1.JDK之ScheduledExecutorService1.2.spring