SpringMVC 使用jndi 多个数据源且利用AbstractRoutingDataSource实现动态数据源切换

SpringMVC 使用jndi 多个数据源且动态切换

 

配合上一章我们来进一步让SpingMVC使用jndi 多个数据源且能够动态切换

 

1.  <beanid="dbe2"class="org.springframework.jndi.JndiObjectFactoryBean">
2.     <propertyname="jndiName">
3.        <value>java:comp/env/jndi/dbe2</value>
4.    </property>
5.    </bean>
6.    <beanid="dbcpccj"class="org.springframework.jndi.JndiObjectFactoryBean">
7.     <propertyname="jndiName">
8.        <value>java:comp/env/jndi/dbcpccj</value>
9.     </property>
10.    </bean>
11.   <beanid="dataSource"class="com.wishbuild.persistent.source.DynamicDataSource">
12.         <propertyname="targetDataSources">  
13.             <mapkey-type="java.lang.String" value-type="com.wishbuild.persistent.source.DataSourceType">  
14.                 <entryvalue-ref="dbe2"key="dbe2"></entry>  
15.                 <entryvalue-ref="dbcpccj"key="dbcpccj"></entry>  
16.             </map>  
17.         </property>  
18.         <propertyname="defaultTargetDataSource"ref="dbe2"></property>  
19.     </bean>   

 

 

 

 

 

 

  • 配置 java 代码

 

 

 

public class DataSourceType {
	public static final String dbe2 = "dbe2";
	public static final String dbcpccj = "dbcpccj";
}
  • 将接收类型定义为String

 

 

public class DataSourceLoadServer {
	private static final ThreadLocal<Object> holder = new ThreadLocal<Object>();

	public static void setDataSourceType(String dbType) {
		holder.set(dbType);
	}

	public static String getDataSourceType() {
		return (String) holder.get();
	}

	public static void clearDataSourceType() {
		holder.remove();
	}
}
  • 利用AbstractRoutingDataSource实现动态数据源切换
public class DynamicDataSource extends AbstractRoutingDataSource {   
	<span style="white-space:pre">	</span>public static final Logger logger = Logger.getLogger(DynamicDataSource.class.toString());
	<span style="white-space:pre">	</span>
	<span style="white-space:pre">	</span>@Override
<span style="white-space:pre">		</span>protected Object determineCurrentLookupKey() {
		<span style="white-space:pre">	</span>String key = DataSourceLoadServer.getDataSourceType();    
		<span style="white-space:pre">	</span>return key;
	<span style="white-space:pre">	</span>}
}
  • 动态切换代码

 

DataSourceLoadServer.setDataSourceType(DataSourceType.dbtest1);

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值