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 ...
随机推荐
- 【转】Spring全家桶
Spring框架自诞生以来一直备受开发者青睐,有人亲切的称之为:Spring 全家桶.它包括SpringMVC.SpringBoot.Spring Cloud.Spring Cloud Dataflo ...
- VIJOS-P1364 Likecloud-吃、吃、吃
JDOJ 1465: VIJOS-P1364 Likecloud-吃.吃.吃 https://neooj.com/oldoj/problem.php?id=1465 Description ...
- STOMP 客户端 API 整理
STOMP(Simple Text-Orientated Messaging Protocol) 面向消息的简单文本协议WebSocket是一个消息架构,不强制使用任何特定的消息协议,它依赖于应用层解 ...
- 使用node.js的http-server开启一个本地服务器
用html写了一个网页,想要在手机上查看适配效果,但是苦于手机上没有直接查看HTML的.想到手机和电脑都在一个局域网内,能不能搭建一个局域网内的网页服务器呢? 1.下载 http-server 显然, ...
- 跑批 - Spring Batch 批处理使用记录
根据spring官网文档提供的spring batch的demo进行小的测验 启动类与原springboot启动类无异 package com.example.batchprocessing; imp ...
- Codeforces Round #530 (Div. 2) F 线段树 + 树形dp(自下往上)
https://codeforces.com/contest/1099/problem/F 题意 一颗n个节点的树上,每个点都有\(x[i]\)个饼干,然后在i节点上吃一个饼干的时间是\(t[i]\) ...
- [LeetCode] 31. Next Permutation 下一个排列
Implement next permutation, which rearranges numbers into the lexicographically next greater permuta ...
- Spring Boot Cache使用与整合
Spring 提供了对缓存功能的抽象:即允许绑定不同的缓存解决方案(如Caffeine.Ehcache等),但本身不直接提供缓存功能的实现.它支持注解方式使用缓存,非常方便. SpringBoot在a ...
- Java连载15-boolean类型&类型转换&++运算符
一.boolean类型 1.说明: (1)在java语言中,boolean类型只有两个值:true.false,没有其他的值.在C语言中,是有0代表false和1代表true的 (2)在底层存储的时候 ...
- bash: telnet: command not found (Linux安装telnet)
问题描述: centos 系统没有 telnet 命令 bash: telnet: command not found 1.安装telnet服务 (3个) yum install xinetd tel ...