public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {
/* 只列出部分代码 */
private Map<Object, Object> targetDataSources;
private Object defaultTargetDataSource;
private boolean lenientFallback = true;
private DataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
private Map<Object, DataSource> resolvedDataSources;
private DataSource resolvedDefaultDataSource;
@Override
public Connection getConnection() throws SQLException {
return determineTargetDataSource().getConnection();
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return determineTargetDataSource().getConnection(username, password);
}
protected DataSource determineTargetDataSource() {
Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
Object lookupKey = determineCurrentLookupKey();
DataSource dataSource = this.resolvedDataSources.get(lookupKey);
if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
dataSource = this.resolvedDefaultDataSource;
}
if (dataSource == null) {
throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
}
return dataSource;
}
protected abstract Object determineCurrentLookupKey();
}
/**
* 获得数据源
*/
public class MultipleDataSource extends AbstractRoutingDataSource{
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceHolder.getRouteKey();
}
}
/**
* 数据源操作类
*/
public class DynamicDataSourceHolder {
private static ThreadLocal<String> routeKey = new ThreadLocal<String>();
/**
* 获取当前线程的数据源路由的key
*/
public static String getRouteKey()
{
String key = routeKey.get();
return key;
}
/**
* 绑定当前线程数据源路由的key
* 使用完成后必须调用removeRouteKey()方法删除
*/
public static void setRouteKey(String key)
{
routeKey.set(key);
}
/**
* 删除与当前线程绑定的数据源路由的key
*/
public static void removeRouteKey()
{
routeKey.remove();
}
}
<!-- 数据源 -->
<bean id="dataSource1" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver">
</property>
<property name="url" value="jdbc:jtds:sqlserver://127.0.0.1;databaseName=test">
</property>
<property name="username" value="***"></property>
<property name="password" value="***"></property>
</bean>
<bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver">
</property>
<property name="url" value="jdbc:jtds:sqlserver://127.0.0.2:1433;databaseName=test">
</property>
<property name="username" value="***"></property>
<property name="password" value="***"></property>
</bean>
<!-- 配置多数据源映射 -->
<bean id="multipleDataSource" class="MultipleDataSource" >
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry value-ref="dataSource1" key="dataSource1"></entry>
<entry value-ref="dataSource2" key="dataSource2"></entry>
</map>
</property>
<!-- 默认数据源 -->
<property name="defaultTargetDataSource" ref="dataSource1" >
</property>
</bean>
DynamicDataSourceHolder.setRouteKey("dataSource2");
@DataSourceKey("dataSource1")
public interface TestEntityMapper extends MSSQLMapper<TestEntity> {
public void insertTest(TestEntity testEntity);
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSourceKey {
String value() default "";
}
public class MultipleDataSourceExchange {
/**
* 拦截目标方法,获取由@DataSource指定的数据源标识,设置到线程存储中以便切换数据源
*/
public void beforeDaoMethod(JoinPoint point) throws Exception {
Class<?> target = point.getTarget().getClass();
MethodSignature signature = (MethodSignature) point.getSignature();
// 默认使用目标类型的注解,如果没有则使用其实现接口的注解类
for (Class<?> cls : target.getInterfaces()) {
resetDataSource(cls, signature.getMethod());
}
resetDataSource(target, signature.getMethod());
}
/**
* 提取目标对象方法注解和类注解中的数据源标识
*/
private void resetDataSource(Class<?> cls, Method method) {
try {
Class<?>[] types = method.getParameterTypes();
// 默认使用类注解
if (cls.isAnnotationPresent(DataSourceKey.class)) {
DataSourceKey source = cls.getAnnotation(DataSourceKey.class);
DynamicDataSourceHolder.setRouteKey(source.value());
}
// 方法注解可以覆盖类注解
Method m = cls.getMethod(method.getName(), types);
if (m != null && m.isAnnotationPresent(DataSourceKey.class)) {
DataSourceKey source = m.getAnnotation(DataSourceKey.class);
DynamicDataSourceHolder.setRouteKey(source.value());
}
} catch (Exception e) {
System.out.println(cls + ":" + e.getMessage());
}
}
}
<bean id="multipleDataSourceExchange" class="MultipleDataSourceExchange "/>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="multipleDataSource" />
</bean>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="insert*" propagation="NESTED" rollback-for="Exception"/>
<tx:method name="add*" propagation="NESTED" rollback-for="Exception"/>
...
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="service" expression="execution(* com.datasource..*.service.*.*(..))"/>
<!-- 注意切换数据源操作要比持久层代码先执行 -->
<aop:advisor advice-ref="multipleDataSourceExchange" pointcut-ref="service" order="1"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="service" order="2"/>
</aop:config>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有