Spring项目配置多数据源
项目中有用到多数据源,并进行动态切换,使用的是阿里的druid。看网上有一篇大致一样的就偷偷懒
import java.sql.SQLFeatureNotSupportedException;
import java.util.Map;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.log4j.Logger;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; import com.xyh.util.SpringUtils; /**
* @author yuanhao
* @describe 实现动态数据源切换逻辑
*/
public class DataSourceUtil extends AbstractRoutingDataSource {
private Logger log = Logger.getLogger(this.getClass());
/**
* 数据源资源池
*/
private Map<Object, Object> _targetDataSources;
/**
* 数据源名称
*/ /**
* @see org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource#determineCurrentLookupKey()
* @describe 数据源为空或者为0时,自动切换至默认数据源
*/
@Override
protected Object determineCurrentLookupKey() {
String dataSourceName = DBContextHolder.getDataSource();
try { if (dataSourceName == null || "".equals(dataSourceName)) {// 如果传入数据源id为空
throw new Exception("传入的数据源名称为空,无法选择数据源");
}
this.selectDataSource(dataSourceName);
} catch (Exception e) {
e.printStackTrace();
}
log.debug("--------> use datasource " + dataSourceName);
return dataSourceName;
}
/**
* @param key
* 数据源id
* @throws Exception
* @describe 数据源存在连接池中时不做处理, 不存在将新数据链接添加至连接池
* /
public void selectDataSource(String dataSourceName) throws Exception { Object obj = this._targetDataSources.get(dataSourceName);
// 如果数据源已经有了
if (obj != null) {
return;
} else {// 如果没有则从spring容器中获取
DruidDataSource dataSource = (DruidDataSource) SpringUtils
.getBeanInstance(dataSourceName);
if (dataSource != null)
this.setDataSource(dataSourceName, dataSource);
else {
throw new Exception("无法取得数据库连接配置,请核对是否已经配置");
}
} } /**
* 将数据源写入池中
* @param key
* @param dataSource
*/
private void setDataSource(String dataSourceName, DruidDataSource dataSource) {
//this.addTargetDataSource(dataSourceName, dataSource);
this._targetDataSources.put(dataSourceName, dataSource);
this.setTargetDataSources(this._targetDataSources);
} @SuppressWarnings({ "unchecked", "rawtypes" })
public void setTargetDataSources(Map targetDataSources) {
this._targetDataSources = targetDataSources;
super.setTargetDataSources(this._targetDataSources);
afterPropertiesSet();
}
/*
public void addTargetDataSource(String key, DruidDataSource dataSource) { }*/
/**
* @return
* @throws SQLFeatureNotSupportedException
*/ public java.util.logging.Logger getParentLogger()
throws SQLFeatureNotSupportedException {
// TODO Auto-generated method stub
return null;
}
}
数据源选择工具类
public class DBContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
/**
* 传入数据源名称
*
* @param key
*/
public static void setDataSource(String key) {
contextHolder.set(key);
}
/**
* 取数据源名称
*
* @return
*/
public static String getDataSource() {
return contextHolder.get();
}
/**
* 销毁数据源名称
*
* @return
*/
public static void clearDataSource() {
contextHolder.remove();
}
}
pring 配置:
<!--db1-->
<bean id="dataSource411602" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close" lazy-init="true">
<property name="driverClassName">
<value>${jdbc.oracle.driverClassName}</value>
</property>
<property name="url">
<value>jdbc:oracle:thin:@192.168.0.1:20003:orcl</value>
</property>
<property name="username">
<value>test</value>
</property>
<property name="password">
<value>test</value>
</property>
<property name="filters" value="stat"></property>
</bean>
<!--db2-->
<bean id="dataSource411606" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close" lazy-init="true">
<property name="driverClassName">
<value>${jdbc.oracle.driverClassName}</value>
</property>
<property name="url">
<value>jdbc:oracle:thin:@192.168.0.2:60021:orcl</value>
</property>
<property name="username">
<value>test</value>
</property>
<property name="password">
<value>test</value>
</property>
<property name="filters" value="stat"></property>
</bean>
<!--数据源-->
<bean id="dataSource" class="com.xyh.util.dbutil.DataSourceUtil">
<property name="targetDataSources">
<map key-type="java.lang.String">
</map>
</property>
</bean>
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocations">
<list>
<value>classpath:sql-map-config.xml</value>
</list>
</property>
<property name="dataSource" ref="dataSource" />
</bean> <!-- JDBC 事务管理 -->
<bean id="jdbcTxManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
使用的时候只需要在要切换数据源的地方写下以下代码DBContextHolder.setDataSource(beanId);数据源就自动切换成你想要使用的那个了!!!
---------------------
原文:https://blog.csdn.net/qq_15541045/article/details/78736526
Spring项目配置多数据源的更多相关文章
- spring项目配置双数据源读写分离
我们最早做新项目的时候一直想做数据库的读写分离与主从同步,由于一些原因一直没有去做这个事情,这次我们需要配置双数据源的起因是因为我们做了一个新项目用了另一个数据库,需要把这个数据库的数据显示到原来的后 ...
- Spring动态配置多数据源
Spring动态配置多数据源,即在大型应用中对数据进行切分,并且采用多个数据库实例进行管理,这样可以有效提高系统的水平伸缩性.而这样的方案就会不同于常见的单一数据实例的方案,这就要程序在运行时根据当时 ...
- 如何通过Spring Boot配置动态数据源访问多个数据库
之前写过一篇博客<Spring+Mybatis+Mysql搭建分布式数据库访问框架>描述如何通过Spring+Mybatis配置动态数据源访问多个数据库.但是之前的方案有一些限制(原博客中 ...
- spring+myBatis 配置多数据源,切换数据源
注:本文来源于 tianzhiwuqis <spring+myBatis 配置多数据源,切换数据源> 一个项目里一般情况下只会使用到一个数据库,但有的需求是要显示其他数据库的内容,像这样 ...
- 一文读懂Spring动态配置多数据源---源码详细分析
Spring动态多数据源源码分析及解读 一.为什么要研究Spring动态多数据源 期初,最开始的原因是:想将答题服务中发送主观题答题数据给批改中间件这块抽象出来, 但这块主要使用的是mq消息的方式 ...
- Spring Boot配置多数据源并实现Druid自动切换
原文:https://blog.csdn.net/acquaintanceship/article/details/75350653 Spring Boot配置多数据源配置yml文件主数据源配置从数据 ...
- Spring+Hibernate配置多数据源
配置说明 在实际应用中,经常会用到读写分离,这里就这种情况进行Spring+Hibernate的多数据源配置.此处的配置只是让读的方法操作一个数据库,写的方法操作另外一个数据库. 注:我这里的配置JD ...
- spring boot 配置双数据源mysql、sqlServer
背景:原来一直都是使用mysql数据库,在application.properties 中配置数据库信息 spring.datasource.url=jdbc:mysql://xxxx/test sp ...
- spring中配置jdbc数据源
1.加入jdbc驱动器包,mysql-connector-java.jar 2.加入commons-dbcp.jar配置数据源 3.在classpath下新建文件jdbc.properties,配置j ...
随机推荐
- TCP数据报结构以及三次握手(九)
TCP(Transmission Control Protocol,传输控制协议)是一种面向连接的.可靠的.基于字节流的通信协议,数据在传输前要建立连接,传输完毕后还要断开连接. 客户端在收发数据前要 ...
- 洛谷 P3998 [SHOI2013]发微博
洛谷 P3998 [SHOI2013]发微博 洛谷传送门 题目描述 刚开通的 SH 微博共有n个用户(1Ln标号),在这短短一个月的时间内, 用户们活动频繁,共有m 条按时间顺序的记录: ! x 表示 ...
- python的开发工具pycharm安装及激活
下面介绍一种较好用也常用的python开发工具Pycharm,此文包括安装及注册激活码 一:安装方法如下: 1:进入官网下载:https://www.jetbrains.com/ 2:下载Commun ...
- hadoop 输入路径用正则表达式被默认处理为多个参数的问题
运行命令 hadoop jar wordcount.jar com.WordCount /inpath/*{beijing,shanghai,guangzhou}* /outpath/ ...
- Codeforces Round #605 (Div. 3) 题解
Three Friends Snow Walking Robot Yet Another Broken Keyboard Remove One Element Nearest Opposite Par ...
- how to design AWS SQS?
遇到这么一题system design,怎么做? 几个月以前,有同事提出要用Webapi代替现有的WCF,当时我投的反对票.而且我给了很充分的理由,不仅仅是时间不足,人手不够,更重要的是这个变化太大, ...
- MySQL实战45讲学习笔记:第八讲
一.今日内容概要 我在第 3 篇文章和你讲事务隔离级别的时候提到过,如果是可重复读隔离级别,事务 T 启动的时候会创建一个视图 read-view,之后事务 T 执行期间,即使有其他事务修改了数据,事 ...
- [LeetCode] 204. Count Primes 质数的个数
Count the number of prime numbers less than a non-negative number, n. Example: Input: 10 Output: 4 E ...
- [LeetCode] 161. One Edit Distance 一个编辑距离
Given two strings s and t, determine if they are both one edit distance apart. Note: There are 3 pos ...
- [转载]3.12 UiPath存在元素Element Exists的介绍和使用
一.Element Exists的介绍 使您能够验证UI元素是否存在,即使它不可见,输出的是一个布尔值 二.Element Exists在UiPath中的使用 1.打开设计器,在设计库中新建一个Seq ...