目錄
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:我碰到了這個問題,找了很多資料,也試了很多次,確沒有一個能用的。然後我又自己研究了一下,感覺還可以,貼出來以免忘記.