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

本文是基于: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">  

 

 

 


 

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
图书管理系统是一个用于管理图书信息的系统,我们可以使用SpringSpring MVCMyBatis实现这个系统。 首先,我们可以使用Spring来创建图书管理系统的核心应用程序。Spring提供了依赖注入、AOP、事务管理等功能,可以帮助我们更好地组织和管理系统的各个模块。通过Spring的配置文件,我们可以配置系统中的Bean并定义它们之间的关系,使系统能够更好地进行扩展和维护。 其次,我们可以使用Spring MVC实现系统的Web层。Spring MVC是一个基于MVC模式的Web框架,可以帮助我们更好地组织和管理用户请求与页面响应。通过Spring MVC,我们可以创建各种Controller来处理用户请求,并将用户的输入数据传递给后端的处理逻辑,最终将处理结果返回给用户。同时,Spring MVC还提供了各种特性,如数据绑定、表单验证、RESTful风格的URL等,能够帮助我们更好地构建用户友好的Web应用程序。 最后,我们可以使用MyBatis实现系统的数据持久层。MyBatis是一个持久层框架,可以帮助我们更好地管理数据库操作。通过MyBatis,我们可以使用XML或者注解的方式来定义数据库操作,同时也可以将数据库操作映射到Java对象,从而简化数据的处理和管理。使用MyBatis,我们可以更好地与数据库交互,提高系统的性能和可维护性。 综上所述,通过使用SpringSpring MVCMyBatis,我们可以更好地实现图书管理系统。这些框架提供了丰富的功能和特性,能够帮助我们更好地组织和管理系统的各个层面,从而实现一个高性能、易扩展、易维护的图书管理系统。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值