目录
2. 使用 DynamicDataSource 动态切换数据源
3.基于xml 写 aop(修改spring-mybatis.xml)
一、jdbc.properties 文件
两个数据库,这里使用的postgresql 数据库
jdbc.driver=org.postgresql.Driver
jdbc.url=jdbc:postgresql://localhost:5432/aaa
jdbc.username=
jdbc.password=
c3p0.maxPoolSize=5
c3p0.minPoolSize=2
c3p0.autoCommitOnClose=false
c3p0.checkoutTimeout=10000
c3p0.maxIdleTime=60
c3p0.idleConnectionTestPeriod=60
c3p0.numHelperThreads=3
c3p0.acquireRetryAttempts=2
jdbc2.driver=org.postgresql.Driver
jdbc2.url=jdbc:postgresql://lcoalhost:5432/bbb
jdbc2.username=
jdbc2.password=
c3p02.maxPoolSize=5
c3p02.minPoolSize=2
c3p02.autoCommitOnClose=false
c3p02.checkoutTimeout=10000
c3p02.maxIdleTime=60
c3p02.idleConnectionTestPeriod=60
c3p02.numHelperThreads=3
c3p02.acquireRetryAttempts=2
二、写 DynamicDataSource 类
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
// 从自定义的位置获取数据源标识
return DynamicDataSourceHolder.getDataSource();
}
}
三、写 DynamicDataSourceHolder 类
public class DynamicDataSourceHolder { /**
* 注意:数据源标识保存在线程变量中,避免多线程操作数据源时互相干扰
*/
private static final ThreadLocal<String> THREAD_DATA_SOURCE = new ThreadLocal<String>();
public static String getDataSource() {
return THREAD_DATA_SOURCE.get();
}
public static void setDataSource(String dataSource) {
THREAD_DATA_SOURCE.set(dataSource);
}
public static void clearDataSource() {
THREAD_DATA_SOURCE.remove();
}
}
四、修改 spring-mybatis.xml 文件
1.定义了两个数据源
<!-- 数据库连接池 -->
<bean id="dataSource1" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
<property name="minPoolSize" value="${c3p0.minPoolSize}"/>
<property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
<property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
<property name="maxIdleTime" value="${c3p0.maxIdleTime}"/>
<property name="idleConnectionTestPeriod" value="${c3p0.idleConnectionTestPeriod}"/>
<property name="numHelperThreads" value="${c3p0.numHelperThreads}"/>
</bean>
<!-- 数据库连接池 -->
<bean id="dataSource2" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc2.driver}"/>
<property name="jdbcUrl" value="${jdbc2.url}"/>
<property name="user" value="${jdbc2.username}"/>
<property name="password" value="${jdbc2.password}"/>
<property name="maxPoolSize" value="${c3p02.maxPoolSize}"/>
<property name="minPoolSize" value="${c3p02.minPoolSize}"/>
<property name="autoCommitOnClose" value="${c3p02.autoCommitOnClose}"/>
<property name="checkoutTimeout" value="${c3p02.checkoutTimeout}"/>
<property name="acquireRetryAttempts" value="${c3p02.acquireRetryAttempts}"/>
<property name="maxIdleTime" value="${c3p02.maxIdleTime}"/>
<property name="idleConnectionTestPeriod" value="${c3p02.idleConnectionTestPeriod}"/>
<property name="numHelperThreads" value="${c3p02.numHelperThreads}"/>
</bean>
2. 使用 DynamicDataSource 动态切换数据源
<bean id="dataSource" class="com.cmbird.Util.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="dataSource1" value-ref="dataSource1"/>
<entry key="dataSource2" value-ref="dataSource2"/>
</map>
</property>
<!--默认数据源-->
<property name="defaultTargetDataSource" ref="dataSource1"/>
</bean>
五、测试
@Test
public void selectByPrimaryKey() throws Exception {
DynamicDataSourceHolder.setDataSource("dataSource2");
System.out.println(iypzdDao.selectYpzdBB());
DynamicDataSourceHolder.setDataSource("dataSource1");
System.out.println(iMapDao.selectMap(true));
}
会发现已经可以自定义切换了,但还是感觉有些麻烦,这时就想到了用spring 自带的AOP 和 自定义注解的思想.
六、自定义注解
1.新建 DataSource 注解接口类
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.TYPE,ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSource {
String value();
}
2.写切面类
import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
public class DataSourceAspect { /**
* 拦截目标方法,获取由@DataSource指定的数据源标识,设置到线程存储中以便切换数据源
*
* @param point
* @throws Exception
*/
public void intercept(JoinPoint point) throws Exception {
Class<?> target = point.getTarget().getClass();
MethodSignature signature = (MethodSignature) point.getSignature();
// 默认使用目标类型的注解,如果没有则使用其实现接口的注解
for (Class<?> clazz : target.getInterfaces()) {
resolveDataSource(clazz, signature.getMethod());
}
resolveDataSource(target, signature.getMethod());
}
/**
* 提取目标对象方法注解和类型注解中的数据源标识
*
* @param clazz
* @param method
*/
private void resolveDataSource(Class<?> clazz, Method method) {
try {
Class<?>[] types = method.getParameterTypes();
// 默认使用类型注解
if (clazz.isAnnotationPresent(DataSource.class)) {
DataSource source = clazz.getAnnotation(DataSource.class);
DynamicDataSourceHolder.setDataSource(source.value());
}
// 方法注解可以覆盖类型注解
Method m = clazz.getMethod(method.getName(), types);
if (m != null && m.isAnnotationPresent(DataSource.class)) {
DataSource source = m.getAnnotation(DataSource.class);
DynamicDataSourceHolder.setDataSource(source.value());
}
} catch (Exception e) {
System.out.println(clazz + ":" + e.getMessage());
}
}
}
3.基于xml 写 aop(修改spring-mybatis.xml)
<bean id="dataSourceAspect" class="com.cmbird.Util.DataSourceAspect" />
<aop:config>
<aop:aspect ref="dataSourceAspect">
<!-- 拦截所有service方法 -->
<aop:pointcut id="dataSourcePointcut" expression="execution(* com.zzz.dao..*.*(..))" />
<aop:before pointcut-ref="dataSourcePointcut" method="intercept" />
</aop:aspect>
</aop:config>
4.大工告成
我写的这个是在 每个dao的接口上添加一个注解 ,比如
@DataSource("dataSource1")
public interface INewsDao {
/**
* 删除数据
* @param id
*/
public void deleteNews(long id);
/**
* 更新修改数据
* @param news
*/
public void updateNews(News news);
/**
* 查询数据
* @param pageInfo
*/
public List<News> selectPageNews(PageInfo pageInfo);
/**
* 查询总数量
*/
public int selectNewsCount();
/**
* 新增数据
* @param news
*/
public void addNews(String news);
public List<News> selectAllNews();
}
就可以使用了.
七、贴一下完整的 spring-mybatis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 扫描service包下所有使用注解的类型 -->
<context:component-scan base-package="com.cmbird.service"/>
<!-- 配置数据库相关参数properties的属性:${url} -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 数据库连接池 -->
<bean id="dataSource1" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
<property name="minPoolSize" value="${c3p0.minPoolSize}"/>
<property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
<property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
<property name="maxIdleTime" value="${c3p0.maxIdleTime}"/>
<property name="idleConnectionTestPeriod" value="${c3p0.idleConnectionTestPeriod}"/>
<property name="numHelperThreads" value="${c3p0.numHelperThreads}"/>
</bean>
<!-- 数据库连接池 -->
<bean id="dataSource2" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc2.driver}"/>
<property name="jdbcUrl" value="${jdbc2.url}"/>
<property name="user" value="${jdbc2.username}"/>
<property name="password" value="${jdbc2.password}"/>
<property name="maxPoolSize" value="${c3p02.maxPoolSize}"/>
<property name="minPoolSize" value="${c3p02.minPoolSize}"/>
<property name="autoCommitOnClose" value="${c3p02.autoCommitOnClose}"/>
<property name="checkoutTimeout" value="${c3p02.checkoutTimeout}"/>
<property name="acquireRetryAttempts" value="${c3p02.acquireRetryAttempts}"/>
<property name="maxIdleTime" value="${c3p02.maxIdleTime}"/>
<property name="idleConnectionTestPeriod" value="${c3p02.idleConnectionTestPeriod}"/>
<property name="numHelperThreads" value="${c3p02.numHelperThreads}"/>
</bean>
<bean id="dataSource" class="com.cmbird.Util.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="dataSource1" value-ref="dataSource1"/>
<entry key="dataSource2" value-ref="dataSource2"/>
</map>
</property>
<!--默认数据源-->
<property name="defaultTargetDataSource" ref="dataSource1"/>
</bean>
<bean id="dataSourceAspect" class="com.cmbird.Util.DataSourceAspect" />
<aop:config>
<aop:aspect ref="dataSourceAspect">
<!-- 拦截所有service方法 -->
<aop:pointcut id="dataSourcePointcut" expression="execution(* com.cmbird.dao..*.*(..))" />
<aop:before pointcut-ref="dataSourcePointcut" method="intercept" />
</aop:aspect>
</aop:config>
<!-- 配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 扫描model包 使用别名 -->
<property name="typeAliasesPackage" value="com.cmbird.model"/>
<!-- 扫描sql配置文件:mapper需要的xml文件 -->
<property name="mapperLocations" value="classpath:mapper/**/*.xml"/>
</bean>
<!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.cmbird.dao"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置基于注解的声明式事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
ps:我碰到了这个问题,找了很多资料,也试了很多次,确没有一个能用的。然后我又自己研究了一下,感觉还可以,贴出来以免忘记.