您的位置:首页 > 编程语言 > Java开发

spring+spring mvc +mybatis+druid 实现数据库主从分离

2016-04-07 18:32 731 查看
本文是基于:spring+spring mvc +mybatis+druid为基础框架, 实现mysql数据库主从分离.

mysql 主从配置(超简单)http://369369.blog.51cto.com/319630/790921/

第一步:基于java annotation(注解)并通过spring aop 实现动态数据源动态选择

package com.wlsq.util;

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* RUNTIME
* 编译器将把注释记录在类文件中,在运行时 VM 将保留注释,因此可以反射性地读取。
* @author yangGuang
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DataSource {
String value();
}


第二步: 实现spring 提供 AbstractRoutingDataSource 类 实现数据源设置

spring  AbstractRoutingDataSource类介绍:http://www.cnblogs.com/surge/p/3582248.html

package com.wlsq.util;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class ChooseDataSource extends AbstractRoutingDataSource  {
/**
* 获取与数据源相关的key
* 此key是Map<String,DataSource> resolvedDataSources 中与数据源绑定的key值
* 在通过determineTargetDataSource获取目标数据源时使用
*/
@Override
protected Object determineCurrentLookupKey() {
// TODO Auto-generated method stub
return HandleDataSource.getDataSource();
}

}


第三步:利用ThreadLocal 解决数据源设置 线程安全性问题

package com.wlsq.util;

/**
* 保存当前线程数据源的key
* @author
* @version 1.0
*
*/
public class HandleDataSource {
public static final ThreadLocal<String> holder = new ThreadLocal<String>();

/**
* 绑定当前线程数据源路由的key
* @param key
*/
public static void putDataSource(String datasource) {
holder.set(datasource);
}

/**
* 获取当前线程的数据源路由的key
* @return
*/
public static String getDataSource() {
return holder.get();
}
}


第四步: 定义一个数据源切面类,通过aop 实现访问,在spring 文件中进行相关的配置工作。

package com.wlsq.util;

import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;

import org.aspectj.lang.reflect.MethodSignature;

/**
* 执行dao方法之前的切面
* 获取datasource对象之前往HandleDataSource中指定当前线程数据源路由的key
* @author Administrator
*
*/
public class DataSourceAspect {

/**
* 在dao层方法之前获取datasource对象之前在切面中指定当前线程数据源路由的key
*/
public void before(JoinPoint point)
{

Object target = point.getTarget();
System.out.println(target.toString());
String method = point.getSignature().getName();
System.out.println(method);
Class<?>[] classz = target.getClass().getInterfaces();
Class<?>[] parameterTypes = ((MethodSignature) point.getSignature())
.getMethod().getParameterTypes();
try {
Method m = classz[0].getMethod(method, parameterTypes);
System.out.println(m.getName());
if (m != null && m.isAnnotationPresent(DataSource.class)) {
DataSource data = m.getAnnotation(DataSource.class);
System.out.println("用户选择数据库库类型:"+data.value());
HandleDataSource.putDataSource(data.value());
}

} catch (Exception e) {
e.printStackTrace();
}
}
}


第五步:配置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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> 
<!-- 开启事务注解驱动 -->
<tx:annotation-driven  transaction-manager="transactionManager"/>

<context:component-scan base-package="com.wlsq">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>

<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>

<bean id="readDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="jdbc:mysql://localhost:3306/wlsq" />
<property name="username" value="root" />
<property name="password" value="123456" />

<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="1" />
<property name="minIdle" value="1" />
<property name="maxActive" value="20" />

<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000" />

<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />

<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />

<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />

<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />

<!-- 配置监控统计拦截的filters -->
<property name="filters" value="stat" />
</bean>

<bean id="writeDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="jdbc:mysql://localhost:3306/wlsqs" />
<property name="username" value="root" />
<property name="password" value="123456" />

<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="1" />
<property name="minIdle" value="1" />
<property name="maxActive" value="20" />

<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000" />

<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />

<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />

<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />

<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />

<!-- 配置监控统计拦截的filters -->
<property name="filters" value="stat" />
</bean>

<bean id="dataSource" class="com.wlsq.util.ChooseDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<!-- write -->
<entry key="write" value-ref="writeDataSource"/>
<!-- read -->
<entry key="read" value-ref="readDataSource"/>
</map>
</property>
<property name="defaultTargetDataSource" ref="readDataSource"/>

</bean>

<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:com/wlsq/mapper/*.xml"></property>
</bean>

<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.wlsq.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>

<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

<!-- 为业务逻辑层的方法解析@DataSource注解  为当前线程的routeholder注入数据源key -->
<bean id="dataSourceAspect" class="com.wlsq.util.DataSourceAspect" />
<aop:config proxy-target-class="true">
<aop:aspect id="dataSourceAspect" ref="dataSourceAspect" order="1">
<aop:pointcut id="tx" expression="execution(* com.wlsq.service..*.*(..)) "/>
<aop:before pointcut-ref="tx" method="before" />
</aop:aspect>
</aop:config>

</beans>


第六步:使用@DataSource 标签,动态选择读写数据库

package com.wlsq.service;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Param;

import com.wlsq.model.News;
import com.wlsq.model.User;
import com.wlsq.util.DataSource;

public interface IUserMapperService {

int deleteByPrimaryKey(Integer userid);

int insert(User record);

int insertSelective(User record);

User selectByPrimaryKey(Integer userid);

int updateByPrimaryKeySelective(User record);

int updateByPrimaryKey(User record);

List<User> selectByObject (User record);

@DataSource("read")
public List<User> selectObject (User record);

@DataSource("write")
public List<News> selectAllUsers(@Param("maps") Map<String, Object> maps);

@DataSource("write")
public int selectCountUsers();
}


学习总结:
第一个错误:Could not open JDBC Connection for transaction; nested exception is java.lang.IllegalStateException: Cannot
determine target DataSource for lookup key [null] 找不到数据源错误

解决办法:事务管理配置一定要配置在,往HandlerDataSource中注入数据源key之前.

第二个错误:spring aop 实现动态数据源选择,但有时存在数据源切换不及时,导致数据查询错误。

解决办法:调整aop 执行排序级别<aop:aspect id="dataSourceAspect" ref="dataSourceAspect" order="1">
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: