简单粗暴的数据源切换

一、定义数据源

1、数据源1和数据源2,spring配置如下代码:

<bean id="masterDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url">
            <value><![CDATA[${oasis.db.url}]]></value>
        </property>
        <property name="username" value="${db.username}"/>
        <property name="password" value="${db.password}"/>

        <property name="initialSize" value="${db.initialSize}"/>
        <property name="minIdle" value="${db.minIdle}"/>
        <property name="maxActive" value="${db.maxActive}"/>
        <property name="maxWait" value="60000" />

        <property name="validationQuery" value="select 1" />

        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <property name="testWhileIdle" value="true" />  <!--建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。-->
        <property name="testOnBorrow" value="false" />  <!--申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。-->
        <property name="testOnReturn" value="false" />  <!--归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能-->
        <property name="connectionProperties" value="useUnicode=true;characterEncoding=utf8;connectTimeout=5000;socketTimeout=60000;autoReconnect=true;failOverReadOnly=false;allowMultiQueries=true"/>

    </bean>

    <bean id="slaveDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url">
            <value><![CDATA[${slave.oasis.db.url}]]></value>
        </property>
        <property name="username" value="${slave.db.username}"/>
        <property name="password" value="${slave.db.password}"/>

        <property name="initialSize" value="${slave.db.initialSize}"/>
        <property name="minIdle" value="${slave.db.minIdle}"/>
        <property name="maxActive" value="${slave.db.maxActive}"/>
        <property name="maxWait" value="60000" />

        <property name="validationQuery" value="select 1" />

        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <property name="testWhileIdle" value="true" />  <!--建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。-->
        <property name="testOnBorrow" value="false" />  <!--申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。-->
        <property name="testOnReturn" value="false" />  <!--归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能-->
        <property name="connectionProperties" value="useUnicode=true;characterEncoding=utf8;connectTimeout=5000;socketTimeout=60000;autoReconnect=true;failOverReadOnly=false"/>

    </bean>

2、总数据源

​ 总的数据源Spring配置如下:

  • DynamicDataSource的写法后边会介绍
    <!-- 配置多数据源映射 -->
    <bean id="dynamicDataSource" class="com.xxx.xxx.helper.datasource.DynamicDataSource">
        <property name="targetDataSources">
            <map key-type="java.lang.String">
                <entry key="master" value-ref="masterDataSource" />
                <entry key="slave" value-ref="slaveDataSource" />
            </map>
        </property>
        <!-- 默认数据源 -->
        <property name="defaultTargetDataSource" ref="masterDataSource" />
    </bean>

二、定义切面

使用AOP拦截特定的注解去动态的切换数据源,代码如下:

 <!-- 数据源Aspect -->
    <bean id="dataSourceAspect" class="com.xxx.xxx.helper.datasource.DataSourceAspect" />

    <!-- 数据源AOP -->
    <aop:config>
        <aop:aspect order="1" ref="dataSourceAspect">
            <aop:pointcut id="dsPointCut" expression="execution(* com.xxxx..*Service.*(..))"/>
            <!--<aop:before pointcut-ref="dsPointCut" method="before"/>-->
            <aop:around pointcut-ref="dsPointCut" method="around" />
        </aop:aspect>
    </aop:config>

三、具体的代码写法

  • 编写AbstractRoutingDataSource的实现类,HandlerDataSource就是提供给我们动态选择数据源的数据的信息,我们这里编写一个根据当前线程来选择数据源,然后通过AOP拦截特定的注解,设置当前的数据源信息,也可以手动的设置当前的数据源,在编程的类中。

  • 数据源切换实现类

    /**
     * 动态数据源抽象实现类(获取数据源对应的key)
     * @Description: 
     * @version 1.0
     */
    public class DynamicDataSource extends AbstractRoutingDataSource {
        @Override
        protected Object determineCurrentLookupKey() {
            return DynamicDataSourceHolder.getDataSourceKey();
        }
    }
    
  • 设置拦截数据源的注解,可以设置在具体的类上,或者在具体的方法上,dataSource是当前数据源的一个别名用于标识我们的数据源的信息,代码如下:

    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.TYPE, ElementType.METHOD })
    public @interface DataSource {
    
        /** 数据源名称 */
        DataSourceEnum value();
    }
    

    枚举类:

    public enum DataSourceEnum {
    
        /** 主库数据源 */
        MASTER("master", "主库数据源"),
        
        /** 从库数据源 */
        SLAVE("slave", "从库数据源");
    
    
        private DataSourceEnum(String key, String description) {
            this.key = key;
            this.description = description;
        }
    
        /** 数据源对应的key(用于在Spring配置文件中指定数据源Map中的key使用) */
        private String key;
    
        /** 说明 */
        private String description;
    
        public String getKey() {
            return key;
        }
    
        public void setKey(String key) {
            this.key = key;
        }
    
        public String getDescription() {
            return description;
        }
    
        public void setDescription(String description) {
            this.description = description;
        }
    }
    
  • AOP拦截类的实现,通过拦截上面的注解,在其执行之前处理设置当前执行SQL的数据源的信息,主要是环绕通知;

    /**
     * @version 1.0
     * @Description: 数据源切面类
     */
    public class DataSourceAspect {
    
        /**
         * 在数据库调用之前进行数据源设置 注:<br/>
         * 对于数据源设置采取就近原则: <br/>
         * 1、如果方法上有数据源设置则以方法为准 <br/>
         * 2、如果方法上没有进行数据源设置则以类上的数据源设置为准
         */
        public void before(JoinPoint joinPoint) {
            // 目标类
            Object target = joinPoint.getTarget();
            // 目标类Class字节码
            Class<?> targetClass = target.getClass();
            // 目标方法的签名
            Signature signature = joinPoint.getSignature();
            // 目标方法名
            String methodName = signature.getName();
            // 目标方法的参数类型数组
            Class<?>[] parameterTypes = ((MethodSignature) signature).getMethod().getParameterTypes();
    
            try {
                DataSource dataSource = null;
                Method method = targetClass.getMethod(methodName, parameterTypes);
                if (method != null && method.isAnnotationPresent(DataSource.class)) // 获取方法上的数据源设置
                    dataSource = method.getAnnotation(DataSource.class);
                else if (targetClass.isAnnotationPresent(DataSource.class)) // 获取类上的数据源设置
                    dataSource = targetClass.getAnnotation(DataSource.class);
    
                if (dataSource != null) {
                    DataSourceEnum dataSourceName = dataSource.value();
                    String key = dataSourceName.getKey();
                    DynamicDataSourceHolder.setDataSourceKey(key);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
            // 目标类
            Object target = proceedingJoinPoint.getTarget();
            // 目标类Class字节码
            Class<?> targetClass = target.getClass();
            // 目标方法的签名
            Signature signature = proceedingJoinPoint.getSignature();
            // 目标方法名
            String methodName = signature.getName();
            // 目标方法的参数类型数组
            Class<?>[] parameterTypes = ((MethodSignature) signature).getMethod().getParameterTypes();
    
            try {
                DataSource dataSource = null;
                Method method = targetClass.getMethod(methodName, parameterTypes);
                if (method != null && method.isAnnotationPresent(DataSource.class)) { // 获取方法上的数据源设置
                    dataSource = method.getAnnotation(DataSource.class);
                } else if (targetClass.isAnnotationPresent(DataSource.class)) { // 获取类上的数据源设置
                    dataSource = targetClass.getAnnotation(DataSource.class);
                }
    
                if (dataSource != null) {
                    DataSourceEnum dataSourceName = dataSource.value();
                    DynamicDataSourceHolder.setDataSourceKey(dataSourceName.getKey());
                }
                return proceedingJoinPoint.proceed();
            } finally {
                DynamicDataSourceHolder.clearDataSourceKey();
            }
        }
    
    
    }
    
    
  • 根据当前线程来选择具体的数据源

    /**
     * 动态数据源持有者
     * @Description:
     * @version 1.0
     */
    public class DynamicDataSourceHolder {
    
        private static ThreadLocal<String> threadLocal = new ThreadLocal<String>();
    
        /**
         * 设置数据源的对应的key
         * 
         * @param key
         *            数据源的对应的key(数据源枚举常量类中对应的key)
         */
        public static void setDataSourceKey(String key) {
            threadLocal.set(key);
        }
    
        /**
         * 获取数据源对应的key
         * 
         * @return String 数据源对应的key
         */
        public static String getDataSourceKey() {
            return threadLocal.get();
        }
    
    
        /**
         * 清空数据源key
         */
        public static void clearDataSourceKey() {
            threadLocal.remove();
        }
    }
    
  • 以上就是动态数据源切换的代码,比如查询的时候,我想用SLAVE从库,在service层加个注解即可,如下:

        @DataSource(DataSourceEnum.SLAVE)
        public Xxxx queryXXXById(String id) {
            return xxxDao.queryXXXById(id);
        }
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。