读写分离切面

package com.iflytek.epdcloud.blp.common.datasource;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import com.iflytek.epdcloud.blp.common.constants.Constants;

/**
 * <b>类 名:</b>SlaveSwitchAspect<br/>
 * <b>类描述:</b>读写分离切面(实现数据库读操作的从库自动切换)<br/>
 

 * 
 */
public class SlaveSwitchAspect implements MethodInterceptor
{

    /**
     * 新增、修改、删除等写数据库方法匹配字符串.
     */
    @SuppressWarnings("unused")
    private static final String[] WRITE_PREFIXS = { "insert", "add", "create", "update", "edit", "modify", "save", "delete", "remove" };

    /**
     * 查询方法匹配字符串.
     */
    private static final String[] READ_PREFIXS = { "get", "query", "find", "select" };

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable
    {
        Object obj;
        // 获取当前设置的数据源,若未设置数据源则默认数据源
        DataSourceType currentDatasource = DataSourceHandle.getDataSouce();
        DataSourceType masterDataSource;
        if (currentDatasource == null)
        {
            masterDataSource = Constants.DEFAULT_DATASOURCE;
        }
        else
        {
            masterDataSource = currentDatasource;
        }
        // 获取执行的方法名称,判断是否为读操作,读操作连从库,写操作必须写入主库
        String methodName = invocation.getMethod().getName();
        boolean isRead = false;
        for (String readPrefix : READ_PREFIXS)
        {
            if (methodName.startsWith(readPrefix))
            {
                isRead = true;
                // 判断设置的数据源从库是否存在,不存在则使用主库
                DataSourceType slaveDataSource = DataSourceType.getValueByName(masterDataSource.name() + "_SLAVE");
                if (null != slaveDataSource)
                {
                    DataSourceHandle.putDataSource(slaveDataSource);
                }
                else
                {
                    DataSourceHandle.putDataSource(masterDataSource);
                }
                break;
            }
        }
        // 不是读操作,切换到当前数据源对应的主库
        if (!isRead)
        {
            DataSourceHandle.putDataSource(masterDataSource);
        }
        obj = invocation.proceed();
        return obj;
    }
}

 

转载于:https://my.oschina.net/mifans/blog/1509958

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值