com.gxl.kratos.jdbc.core.SwitchDataSource.java Source code

Java tutorial

Introduction

Here is the source code for com.gxl.kratos.jdbc.core.SwitchDataSource.java

Source

/*
 * Copyright 2015-2101 gaoxianglong
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gxl.kratos.jdbc.core;

import java.util.Arrays;
import java.util.List;
import javax.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gxl.kratos.jdbc.datasource.config.DataSourceHolder;
import com.gxl.kratos.jdbc.exception.ShardException;
import com.gxl.kratos.jdbc.mysql.sql.parser.SqlParser;
import com.gxl.kratos.jdbc.shard.DbRule;
import com.gxl.kratos.jdbc.shard.GetKeyName;
import com.gxl.kratos.jdbc.shard.TbRule;

/**
 * SpringAop?????
 * 
 * @author gaoxianglong
 */
@Aspect
public class SwitchDataSource {
    private static Logger logger = LoggerFactory.getLogger(SwitchDataSource.class);
    @Resource
    private KratosJdbcTemplate kJdbcTemplate;
    @Resource
    private DataSourceHolder dataSourceHolder;
    @Resource
    private DbRule dbRule;
    @Resource
    private TbRule tbRule;
    @Resource
    private SqlParser sqlParser;
    @Resource
    private SwitchTab switchTab;

    /**
     * SpringAop?JdbcTemplateupdate
     * 
     * @author gaoxianglong
     * 
     * @param proceedingJoinPoint
     *            ?
     * 
     * @exception Throwable
     * 
     * @return Object
     */
    @Around("execution(* com.gxl.kratos.jdbc.core.KratosJdbcTemplate.update*(..))")
    public Object interceptUpdate(ProceedingJoinPoint proceedingJoinPoint) {
        return execute(proceedingJoinPoint, true);
    }

    /**
     * SpringAop?JdbcTemplatequery
     * 
     * @author gaoxianglong
     * 
     * @param proceedingJoinPoint
     *            ?
     * 
     * @exception Throwable
     * 
     * @return Object
     */
    @Around("execution(* com.gxl.kratos.jdbc.core.KratosJdbcTemplate.query*(..))")
    public Object interceptQuery(ProceedingJoinPoint proceedingJoinPoint) {
        return execute(proceedingJoinPoint, false);
    }

    /**
     * ???
     * 
     * @author gaoxianglong
     * 
     * @param proceedingJoinPoint
     *            ?
     * 
     * @param operation
     *            truemaster?falseslave?
     * 
     * @exception Throwable
     * 
     * @return Object
     */
    public Object execute(ProceedingJoinPoint proceedingJoinPoint, boolean operation) {
        long befor = System.currentTimeMillis();
        Object result = null;
        /* ?? */
        Object[] params = proceedingJoinPoint.getArgs();
        Object param = params[0];
        if (param.getClass() == String.class) {
            final String SQL = (String) param;
            logger.info("??sql-->" + SQL);
            /* ??? */
            if (kJdbcTemplate.getIsShard()) {
                /* ? */
                if (kJdbcTemplate.getShardMode()) {
                    /* ? */
                    logger.debug("??");
                    params = oneTbshard(SQL, params, operation).toArray();
                } else {
                    /* ? */
                    logger.debug("??");
                    params = manyTbshard(SQL, params, operation).toArray();
                }
                String NEW_SQL = params[0].toString();
                logger.info("sharding??sql-->" + NEW_SQL);
            } else {
                /* ?/ */
                int index = WeightResolver.getIndex(kJdbcTemplate.getWr_weight(), operation);
                /* ???master */
                setRoutingIndex(index);
            }
            try {
                /*  */
                result = proceedingJoinPoint.proceed(params);
                logger.debug("->" + (System.currentTimeMillis() - befor) + "ms");
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * ?
     * 
     * @author gaoxianglong
     * 
     * @param sql
     *            ??sql?
     * 
     * @param params
     *            ?
     * 
     * @param operation
     *            truemaster?falseslave?
     * 
     * @exception ShardException
     * 
     * @return List<Object> ???
     */
    protected List<Object> manyTbshard(String sql, Object[] params, boolean operation) {
        /* ??? */
        String dbRuleArray = kJdbcTemplate.getDbRuleArray();
        /* ??? */
        String tbRuleArray = kJdbcTemplate.getTbRuleArray();
        /* ?? */
        List<String> keyNames = GetKeyName.getName(false, dbRuleArray, tbRuleArray);
        /* ?? */
        long key = sqlParser.getKey(sql, keyNames);
        /* ?? */
        int dbIndex = dbRule.getIndex(key, dbRuleArray);
        /* ? */
        int tbIndex = tbRule.getIndex(key, tbRuleArray);
        /* ????? */
        String values[] = tbRuleArray.split("[\\%]");
        int tbSize = Integer.parseInt(values[1]);
        int dbSize = Integer.parseInt(values[2]);
        /* ????sql */
        String newSql = switchTab.setTabName(dbIndex, tbIndex, dbSize, tbSize, kJdbcTemplate.getConsistent(),
                sqlParser.getTbName(sql), sql);
        /* ??master/slave??? */
        int index = WeightResolver.getIndex(kJdbcTemplate.getWr_weight(), operation);
        dbIndex += index;
        /* ??? */
        setRoutingIndex(dbIndex);
        /* ???? */
        List<Object> newParams = Arrays.asList(params);
        newParams.set(0, newSql);
        return newParams;
    }

    /**
     * ?
     * 
     * @author gaoxianglong
     * 
     * @param sql
     *            ??sql?
     * 
     * @param params
     *            ?
     * 
     * @param operation
     *            truemaster?falseslave?
     * 
     * @exception ShardException
     * 
     * @return List<Object> ???
     */
    protected List<Object> oneTbshard(String sql, Object[] params, boolean operation) {
        /* ??? */
        String dbRuleArray = kJdbcTemplate.getDbRuleArray();
        /* ?? */
        List<String> keyNames = GetKeyName.getName(true, dbRuleArray, null);
        /* ?? */
        long key = sqlParser.getKey(sql, keyNames);
        /* ?? */
        int dbIndex = dbRule.getIndex(key, dbRuleArray);
        String newSql = null;
        if (kJdbcTemplate.getConsistent()) {
            /* ????sql */
            newSql = switchTab.setTabName(dbIndex, sqlParser.getTbName(sql), sql);
        } else {
            newSql = sql;
        }
        /* ??master/slave??? */
        int index = WeightResolver.getIndex(kJdbcTemplate.getWr_weight(), operation);
        dbIndex += index;
        /* ??? */
        setRoutingIndex(dbIndex);
        /* ???? */
        List<Object> newParams = Arrays.asList(params);
        newParams.set(0, newSql);
        return newParams;
    }

    /**
     * ???
     * 
     * @author gaoxianglong
     * 
     * @param dbIndex
     *            ?
     * 
     * @return void
     */
    private void setRoutingIndex(int dbIndex) {
        dataSourceHolder.setRoutingIndex(dbIndex);
        logger.info("kratos????,????-->" + dbIndex);
    }
}