方案一
1、spring的applicationContext.xml中的配置
<bean id="masterDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="jdbc:postgresql://127.0.0.1:5432/zcaqs"/>
<property name="username" value="postgres"/>
<property name="password" value="123456"/>
<property name="initialSize" value="1"/>
<property name="maxActive" value="20"/>
<property name="testOnBorrow" value="false"/>
<property name="testWhileIdle" value="true"/>
<property name="filters" value="stat"/>
</bean>
<bean id="slaveDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="jdbc:postgresql://127.0.0.1:5432/zcaqs"/>
<property name="username" value="postgres"/>
<property name="password" value="123456"/>
<property name="initialSize" value="1"/>
<property name="maxActive" value="20"/>
<property name="testOnBorrow" value="false"/>
<property name="testWhileIdle" value="true"/>
<property name="filters" value="stat"/>
<!--開啓監控-->
</bean>
<bean id="dataSource" class="org.akzx.acaqs.base.database.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="slave" value-ref="slaveDataSource"/>
</map>
</property>
<property name="defaultTargetDataSource" ref="masterDataSource"/>
</bean>
<!-- 切換數據源 -->
<bean id="dataSourceAdvice" class="org.akzx.acaqs.base.database.DataSourceAdvice"/>
<aop:config>
<aop:advisor
pointcut="execution(* org.akzx.acaqs.service..*Service.*(..))"
advice-ref="dataSourceAdvice"/>
</aop:config>
2、兩個需要實現的bean類
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceSwitcher.getDataSource();
}
}
public class DataSourceAdvice implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice {
// service方法執行之前被調用
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println("切入點: " + target.getClass().getName() + "類中" + method.getName() + "方法");
if (method.getName().startsWith("add")
|| method.getName().startsWith("create")
|| method.getName().startsWith("save")
|| method.getName().startsWith("edit")
|| method.getName().startsWith("update")
|| method.getName().startsWith("delete")
|| method.getName().startsWith("remove")) {
System.out.println("切換到: master");
DataSourceSwitcher.setMaster();
} else {
System.out.println("切換到: slave");
DataSourceSwitcher.setSlave();
}
}
// service方法執行完之後被調用
public void afterReturning(Object arg0, Method method, Object[] args, Object target) throws Throwable {
}
// 拋出Exception之後被調用
public void afterThrowing(Method method, Object[] args, Object target, Exception ex) throws Throwable {
DataSourceSwitcher.setSlave();
System.out.println("出現異常,切換到: slave");
}
}
以上方法有很多缺點,限制,使用的方法二是以註解的形式實現
方案二(預備)