继昨天的Mysql主从的概述及基本的配置。今天趁着不是很忙的时候整理一下主从JAVA端的代码实现。下面开始贴代码:
Spring MVC 的datasorce配置,这里我们使用的阿里的druid(德鲁伊)数据库连接池,先配置两个数据库链接池。分别连接主、从两个库。然后使用spring 的一个主要特性AOP切面编程来根据方法的前缀命名来选择是使用主数据库还是使用从数据库。(我选择切的是controller层,当用户访问方法的 时候,我就已经决定了是选择哪个数据源进行处理)
<?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: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-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">
<!-- spring-datasource.xml 主要进行应用程序数据源的分配。根据请求的方法名称规范,自动分配主/从数据库 -->
<!-- 配置数据源 -->
<bean name="dataSourceMaster" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${master_jdbc_url}" />
<property name="username" value="${master_jdbc_username}" />
<property name="password" value="${master_jdbc_password}" />
<property name="initialSize" value="${initialSize}" />
<property name="maxActive" value="${maxActive}" />
<property name="maxIdle" value="${maxIdle}" />
<property name="minIdle" value="${minIdle}" />
<property name="maxWait" value="${maxWait}" />
<property name="validationQuery" value="${validationQuery}" />
<property name="testOnBorrow" value="${testOnBorrow}" />
<property name="testOnReturn" value="${testOnReturn}" />
<property name="testWhileIdle" value="${testWhileIdle}" />
<property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
<property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
<property name="removeAbandoned" value="${removeAbandoned}" />
<property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />
<property name="logAbandoned" value="${logAbandoned}" />
<property name="filters" value="stat" />
</bean>
<!-- 配置数据源 -->
<bean name="dataSourceSlave" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${slave_jdbc_url}" />
<property name=&#