spring 配置多数据源(mysql读写分离)

  前段时间刚换了家新公司,然后看项目代码里用了数据库读写分离的架构,然后好奇扒了代码简单看了下,总体来说就是运用spring aop切面方式来实现的。看明白后就在自己的个人小项目里运用了下,测试OK,所以下面总结下流程:

  1、首先定义一个数据源注解,它有两个值,一个对应写库(主库),一个对应读库(从库)

package com.jdd.ds;

import java.lang.annotation.*;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {

    String DATA_SOURCE_READ = "dataSourceRead";
    String DATA_SOURCE_WRITE = "dataSourceWrite";

    String name() default "dataSourceWrite";
}

  2、在需要拦截的方法上加上该注解

package com.jdd.service.impl;

import com.jdd.dao.UserDao;
import com.jdd.ds.DataSource;
import com.jdd.pojo.User;
import com.jdd.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("userService")
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDao userDao;

    @DataSource(name=DataSource.DATA_SOURCE_READ)
    @Override
    public User getUserByNameAndPassword(String name, String password) {
        return userDao.getUserByNameAndPassword(name, password);
    }

    @DataSource(name=DataSource.DATA_SOURCE_WRITE)
    @Override
    public int insertUser(User user) {
        return userDao.insertUser(user);
    }
}

  3、然后在配置文件里加上aop切面配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/aop http://www.springframework.org/schema/aop/spring-aop-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/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 扫描包加载Service实现类 -->
    <context:component-scan base-package="com.jdd.service"></context:component-scan>

    <bean id="dataSourceExchange" class="com.jdd.ds.DataSourceExchange"></bean>
    <aop:config>
        <aop:aspect ref="dataSourceExchange">
            <aop:around method="execute" pointcut="within(com.jdd.service.impl.*)"></aop:around>
        </aop:aspect>
    </aop:config>

</beans>

  4、然后我们要在切面类里,获取到方法上的dataSource注解里设置的值,从而决定使用哪个数据源

package com.jdd.ds;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

public class DataSourceExchange {

    private static Logger logger = LoggerFactory.getLogger(DataSourceExchange.class);

    public Object execute(ProceedingJoinPoint pjp){

        logger.info("DataSourceExchange==>");
        Object obj = null;

        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature)signature;
        Method targetMethod = methodSignature.getMethod();
        Method realMethod = null;
        try {
            realMethod = pjp.getTarget().getClass().getDeclaredMethod(signature.getName(), targetMethod.getParameterTypes());
            if(realMethod.isAnnotationPresent(DataSource.class)){
                DataSource datasource = (DataSource) realMethod.getAnnotation(DataSource.class);
                DataSourceContext.setDbType(datasource.name());
                logger.info(realMethod.getName() +" set dbtype==>"+datasource.name());
            }else{
                DataSourceContext.setDbType("dataSourceWrite");
            }
            obj = pjp.proceed();
        } catch (Throwable t) {
            t.printStackTrace();
        }
        logger.info(realMethod.getName()+" clear datatype==>");
        DataSourceContext.clearDbType();
        return obj;

    }

}

  在方法执行前,设置具体数据源,然后方法执行完后,再清除掉该值。

  注:注意上面的通过反射获取业务方法的代码, 开始的时候用

  MethodSignature signature = (MethodSignature)pjp.getSignature();

  Method method = signature.getMethod();

  发现通过这种方法获取的method,它是没有注解信息的。后来在网上搜了下,大概说是这种方法获取的是代理方法,不是目标方法。代理方法是不带注解信息的,所以这块注意下。

  5、下面看下 DataSourceContext 类,作用自然就是设置数据源上下文。

package com.jdd.ds;

public class DataSourceContext {

    public static final String DATA_SOURCE_READ = "dataSourceRead";
    public static final String DATA_SOURCE_WRITE = "dataSourceWrite";
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

    public DataSourceContext(){
    }

    public static void setDbType(String dbType){
        contextHolder.set(dbType);
    }

    public static String getDbType(){
        return (String)contextHolder.get();
    }

    public static void clearDbType(){
        contextHolder.remove();
    }

}

  6、下面定义 MultipleDataSource类, 继承与spring的 AbstractRoutingDataSource类, 并重写它的 determineCurrentLookupKey 方法, 作用就是从上下文获取当前线程使用的数据源标识:

package com.jdd.ds;

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

public class MultipleDataSource extends AbstractRoutingDataSource{

    @Override
    protected Object determineCurrentLookupKey() {

        Object key = DataSourceContext.getDbType();
        if(key != null){
            this.logger.info("当前线程使用的数据源标识为 [ " + key.toString() + " ].");
        }
        return key;
    }
}

  7、最后在 配置文件 applicationContext-mysql.xml 里 配上数据源

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/aop http://www.springframework.org/schema/aop/spring-aop-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/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:resource/*.properties" />

    <!-- 数据库连接池 -->
    <bean id="dataSourceWrite" class="com.alibaba.druid.pool.DruidDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="${url.write}" />
        <property name="username" value="${username.write}" />
        <property name="password" value="${password.write}" />
        <property name="maxActive" value="10" />
        <property name="minIdle" value="5" />
    </bean>

    <bean id="dataSourceRead" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="${url.read}" />
        <property name="username" value="${username.read}" />
        <property name="password" value="${password.read}" />
        <property name="maxActive" value="10" />
        <property name="minIdle" value="5" />
    </bean>
    <bean id="multipleDataSource" class="com.jdd.ds.MultipleDataSource">
        <property name="defaultTargetDataSource" ref="dataSourceWrite" />
        <property name="targetDataSources">
            <map>
                <entry value-ref="dataSourceWrite" key="dataSourceWrite"></entry>
                <entry value-ref="dataSourceRead" key="dataSourceRead"></entry>
            </map>
        </property>
    </bean>
    <!-- sqlsessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
        <property name="dataSource" ref="multipleDataSource"></property>
        <property name="mapperLocations" value="classpath:com/jdd/mapper/*.xml"></property>
    </bean>

</beans>

  8、到这里和spring相关的配置基本就配完了, 其实后面还要再配置一下 mysql的主从复制,就是对写库的操作都同步到从库,这样写库从库的数据才一致。具体配置操作我就不写了,可以自行到网上搜索。

原文地址:https://www.cnblogs.com/xiexin2015/p/8998647.html

时间: 2024-08-01 20:13:54

spring 配置多数据源(mysql读写分离)的相关文章

spring 配置双数据源并读写分离

摘自 开源项目Ibase4j    关键思想在于AbstractRoutingSource 类 还有方法名称和切入点去控制使用哪个数据源    1.首先在配置文件配置多个数据源 并且交给继承自spring AbstractRoutingSource去管理 datasource.xml配置如下 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springfram

spring hibernate配置切换数据源,实现读写分离

spring的配置如下 <!-- 主数据源--> <bean id="masterDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <prope

spring学习笔记(19)mysql读写分离后端AOP控制实例

在这里,我们接上一篇文章,利用JNDI访问应用服务器配置的两个数据源来模拟同时操作不同的数据库如同时操作mysql和oracle等.实际上,上个例子可能用来模拟mysql数据库主从配置读写分离更贴切些.既然如此,在本例中,我们就完成读写分离的模拟在web端的配置实例. 续上次的例子,关于JNDI数据源的配置和spring datasource的配置这里不再重复.下面着重加入AOP实现DAO层动态分库调用.可先看上篇文章<spring学习笔记(18)使用JNDI模拟访问应用服务器多数据源实例 >

Spring+Hibernate框架下Mysql读写分离、主从数据库配置

1. 配置AOP切面类 DataSourceAdvice.java package until; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; import org.springframework.aop.MethodBeforeAdvice; import org.springframework.aop.ThrowsAdvice; public class DataSo

MySQL 读写分离 (基于Amoeba)

一.MySQL读写分离原理 主数据库处理事务性查询,从数据库处理select查询.数据库复制用来把事务性查询导致的变更同步到从数据库中. 二.最为常见的读写分离有两种: 1.基于程序代码实现 在代码中根据select,insert进程路由分类: 优点:性能好,因为在代码中实现,不需要额外的硬件设备: 缺点:需要开发人员来实现,对代码改动比较大,不适合大型复杂应用: 2.基于代理层实现 MySQL-Proxy:隶属于MySQL开源项目: Amoeba:Amoeba是一个以MySQL为底层数据存储,

Spring配置动态数据源-读写分离和多数据源

在现在互联网系统中,随着用户量的增长,单数据源通常无法满足系统的负载要求.因此为了解决用户量增长带来的压力,在数据库层面会采用读写分离技术和数据库拆分等技术.读写分离就是就是一个Master数据库,多个Slave数据库,Master数据库负责数据的写操作,slave库负责数据读操作,通过slave库来降低Master库的负载.因为在实际的应用中,数据库都是读多写少(读取数据的频率高,更新数据的频率相对较少),而读取数据通常耗时比较长,占用数据库服务器的CPU较多,从而影响用户体验.我们通常的做法

使用Atlas实现MySQL读写分离+MySQL-(Master-Slave)配置

参考博文: MySQL-(Master-Slave)配置  本人按照博友北在北方的配置已成功  我使用的是 mysql5.6.27版本. 使用Atlas实现MySQL读写分离

配置 Mysql 读写分离+强制走写节点+根据主从延时的读写分离

配置 Mysql 读写分离+强制走写节点+根据主从延时的读写分离http://www.linuxmysql.com/14/2019/1008.htm 原文地址:https://blog.51cto.com/rscpass/2423421

Spring+Mybatis实现主从数据库读写分离

Spring+Mybatis实现主从数据库读写分离 采用配置+注解的方式. 自定义@DataSource注解 import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME

构建高性能web之路------mysql读写分离实战

一个完整的mysql读写分离环境包括以下几个部分: 应用程序client database proxy database集群 在本次实战中,应用程序client基于c3p0连接后端的database proxy.database proxy负责管理client实际访问database的路由策略,采用开源框架amoeba.database集群采用mysql的master-slave的replication方案.整个环境的结构图如下所示: 实战步骤与详解 一.搭建mysql的master-slave