spring解决数据库读写分离

公司项目是电子商务系统,由于数据量较大,同时并发量也比较大,所以项目才有了分布式部署,数据库方面,采用了主从复制(读写分离),所以程序里面要是实现多数据的动态

切换,本文直说程序里面如何实现数据源动态切换:


本文介绍的是没有加入任何其他中间件,直接在程序里面实现数据源的动态企业换:

1、不支持@Transactional注解事务。

  2、必须按照配置约定进行配置,不够灵活。

其他不多说啦,直接上代码:

package com.test.utils.dataSource;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * 
 * @ClassName: DataSource
 * @Description:<p>定义注解标签类</p>
 * @author 李建行
 * @date 2015-5-11
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DataSource{
String value();
}



package com.test.utils.dataSource;


import org.aspectj.lang.JoinPoint;
public interface AspectAop {
public void before(JoinPoint point);
}


package com.test.utils.dataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
 * 
 * @ClassName: DynamicDataSource
 * @Description:<p>项目启动时加载spring容器,并将读,写数据源放入到sprig容器里面</p>
 * @author 李建行
 * @date 2015-5-11
 */
public class DynamicDataSource extends AbstractRoutingDataSource{
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceHolder.getDataSouce();
}
}

package com.test.utils.dataSource;
/**
 * 
 * @ClassName: DynamicDataSourceHolder
 * @Description:<p>为每一个线程放入数据源或者获取数据源</p>
 * @author 李建行
 * @date 2015-5-11
 */
public class DynamicDataSourceHolder {
public static final ThreadLocal<String> holder = new ThreadLocal<String>();
    public static void putDataSource(String name) {
        holder.set(name);
    }
    public static String getDataSouce() {
        return holder.get();
    }
}


package com.test.utils.dataSource;
import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
/**
 * 
 * @ClassName: DataSourceAspect
 * @Description:<p>功能描述:通过aop实现对dataSource的动态赋值</p>
 * @author 李建行
 * @date 2015-4-22
 */
public class DataSourceAspect{

public void before(JoinPoint point) {
Object target = point.getTarget();
        String method = point.getSignature().getName();
        Class<?>[] classz = target.getClass().getInterfaces();
        Class<?>[] parameterTypes = ((MethodSignature) point.getSignature())
                .getMethod().getParameterTypes();
        try {
            Method m = classz[0].getMethod(method, parameterTypes);
            if (m != null && m.isAnnotationPresent(DataSource.class)) {
                DataSource data = m.getAnnotation(DataSource.class);
                DynamicDataSourceHolder.putDataSource(data.value());
                System.out.println("数据源:"+data.value());
            }
        } catch (Exception e) {
            
        }
}

}

spring的配置文件:


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
">
<context:property-placeholder location="classpath:dataSource.properties" />
<bean id="writeDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${auto.jdbc.driverClass}" />
<property name="url" value="${auto.jdbc.writeJdbcUrl}" />
<property name="username" value="${auto.jdbc.user}" />
<property name="password" value="${auto.jdbc.password}" />
<property name="initialSize" value="${auto.jdbc.initialPoolSize}" />
<property name="maxActive" value="${auto.jdbc.maxPoolSize}" />
<property name="maxWait" value="${auto.jdbc.maxWait}" />
<property name="useUnfairLock" value="true"/>
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="${auto.jdbc.timeBetween}" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="${auto.jdbc.minEvictable}" />
<property name="validationQuery" value="select current_date" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="maxOpenPreparedStatements" value="${auto.jdbc.maxOpen}" />
<property name="filters" value="stat" />
</bean>
<!-- 读的数据源 com.alibaba.druid.pool.DruidDataSource-->
<bean id="readDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${auto.jdbc.driverClass}" />
<property name="url" value="${auto.jdbc.readJdbcUrl}" />
<property name="username" value="${auto.jdbc.user}" />
<property name="password" value="${auto.jdbc.password}" />
<property name="initialSize" value="${auto.jdbc.initialPoolSize}" />
<property name="maxActive" value="${auto.jdbc.maxPoolSize}" />
<property name="maxWait" value="${auto.jdbc.maxWait}" />
<property name="useUnfairLock" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="${auto.jdbc.timeBetween}" />
<property name="minEvictableIdleTimeMillis" value="${auto.jdbc.minEvictable}" />
<property name="validationQuery" value="select current_date" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="maxOpenPreparedStatements" value="${auto.jdbc.maxOpen}" />
<property name="filters" value="stat" />
</bean>
<bean id="dataSource" class="com.hsi.utils.dataSource.DynamicDataSource">
        <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>
    <!-- 配置数据库注解aop -->
    <aop:aspectj-autoproxy/>
    <bean id="manyDataSourceAspect" class="com.hsi.utils.dataSource.DataSourceAspect" />
 
    <aop:config>
        <aop:aspect id="c" ref="manyDataSourceAspect">
            <aop:pointcut id="tx"  expression="execution(* com.hs.*.*.service.impl.*.*(..))"/>
            <aop:before pointcut-ref="tx" method="before"/>
        </aop:aspect>
    </aop:config>
<!-- 配置myBATIS -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<!-- 该配置文件用来指定Mapper映射文件的位置 ,映射文件名必须与接口同名 -->
<property name="mapperLocations" value="classpath:com.hs.*.*.persistent.*.xml"/>
<!--configLocation属性指定mybatis的核心配置文件--> 
      <property name="configLocation" value="classpath:SqlMapConfig.xml" /> 
</bean>

<!-- 自动查找package下的类为它 们 创 建 成 MapperFactoryBean。 -->
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.hs.**.persistent" />
</bean>

<!-- 方便执行自定义的 sql  -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
<constructor-arg index="1" value="BATCH" /> 
</bean>

   <!-- 新增mvc json的支持 -->
    <mvc:annotation-driven>
   <mvc:message-converters register-defaults="true">
     <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
       <property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>
       <property name="features">
        <array>
        <value>WriteMapNullValue</value>
            <value>WriteNullStringAsEmpty</value>
        </array>
       </property>
     </bean>
   </mvc:message-converters>
  </mvc:annotation-driven>


    <context:annotation-config />
    <context:component-scan base-package="com.hs"/>
<mvc:annotation-driven />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/page/" />
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="multipartResolver"  
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!-- set the max upload size100MB -->  
        <property name="maxUploadSize">  
            <value>104857600</value>  
        </property>
        <!-- 这个默认是10K  设成16M好了  大于这个大小的文件会放到临时目录 ,否则会报can't read again 的错误 -->  
      <property name="maxInMemorySize">  
            <value>1638400</value>  
        </property>
    </bean>  
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="writeDataSource" />
</bean>
<!--配置事务的传播特性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" read-only="false" propagation="REQUIRED" />
<tx:method name="insert*" read-only="false" propagation="REQUIRED" />
<tx:method name="delete*" read-only="false" propagation="REQUIRED" />
<tx:method name="remove*" read-only="false" propagation="REQUIRED" />
<tx:method name="modify*" read-only="false" propagation="REQUIRED" />
<tx:method name="update*" read-only="false" propagation="REQUIRED" />
<tx:method name="save*" read-only="false" propagation="REQUIRED" />
<tx:method name="put*"  read-only="true"/>  
        <tx:method name="query*"  read-only="true"/>  
       <tx:method name="use*"  read-only="true"/>  
       <tx:method name="get*"  read-only="true" />  
        <tx:method name="count*"  read-only="true" />  
        <tx:method name="find*"  read-only="true" />  
       <tx:method name="list*"  read-only="true" />
        <tx:method name="*" read-only="false" propagation="REQUIRED"/> 
</tx:attributes>
</tx:advice>
<!--那些类的哪些方法参与事务 -->
<aop:config>
<aop:pointcut id="allManagerMethod"
expression="execution(* com.hs.*.*.service.impl.*.*(..))" />
<aop:advisor pointcut-ref="allManagerMethod" advice-ref="txAdvice" />
</aop:config>
</beans>

java 代码测试类:

接口

public interface AreMarketZoneService {

/**

* @Description:<p>功能描述:添加商圈</p>
* @param AreMarketZone
* @author 李建行
* @date   2015-4-23
*/
public void add(AreMarketZone areMarketZone);

}

实现类:



@Service
public class AreMarketZoneServiceImpl implements AreMarketZoneService {

        @Override
@DataSource("write")
public void add(AreMarketZone areMarketZone) {
Users users = SecuritySessionUtils.getUserInfor();
String selectCondition=areMarketZone.getState()+areMarketZone.getCity()+areMarketZone.getDistrict();
AreAddress areAdddress= areaAddressMapper.selectIsExistAddress(selectCondition);
if(areAdddress==null){
areAdddress = new AreAddress();
Long sequence = areaAddressMapper.getSequence();
areAdddress.setAddrid(sequence);
areAdddress.setAddressid(sequence);
areAdddress.setAddress(selectCondition);
areAdddress.setStateid(areMarketZone.getStateid());
areAdddress.setState(areMarketZone.getState());
areAdddress.setCityid(areMarketZone.getCityid());
areAdddress.setCity(areMarketZone.getCity());
areAdddress.setDistrictid(areMarketZone.getDistrictid());
areAdddress.setDistrict(areMarketZone.getDistrict());
areAdddress.setCrtusrid(users.getUsrid());
areAdddress.setCrtusr(users.getUsrname());
areAdddress.setCrtdate(new Date());
areAdddress.setRemarks(areMarketZone.getRemarks());
areaAddressMapper.insertSelective(areAdddress);
}
Area state = areaService.findById(areMarketZone.getStateid()+"");
Area statezone = areaService.findById(state.getUpareid()+"");
Integer sequence = areMarketZoneMapper.selectSequence();
areMarketZone.setUsrmzoneid(sequence);
areMarketZone.setLocmzoneid(sequence);
areMarketZone.setStatezone(statezone.getAreades());
areMarketZone.setStatezoneid(statezone.getAreaid());
areMarketZone.setCrtdate(new Date());
areMarketZone.setCrtusr(users.getUsrname());
areMarketZone.setCrtusrid(users.getUsrid());
areMarketZoneMapper.insertSelective(areMarketZone);
}

}


完工,希望能对大家有所帮助!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值