sharding sphere 4.1.1 - “路由装饰器RouteDecorator-主从” 之 “控制强制读主库”

.

MasterVisitedManager.setMasterVisited();

org.apache.shardingsphere.masterslave.route.engine.MasterSlaveRouteDecorator#decorate
org.apache.shardingsphere.masterslave.route.engine.impl.MasterSlaveDataSourceRouter#route
org.apache.shardingsphere.masterslave.route.engine.impl.MasterSlaveDataSourceRouter#isMasterRoute

public final class MasterSlaveDataSourceRouter {
    
    private final MasterSlaveRule masterSlaveRule;
    
    /**
     */
    public String route(final SQLStatement sqlStatement) {
    	// 1、检查是否要执行走主库逻辑(非select、sql语句存在锁标记、强制标记走主库、是否有hint标记)
        if (isMasterRoute(sqlStatement)) {
            MasterVisitedManager.setMasterVisited();
            return masterSlaveRule.getMasterDataSourceName();
        }

        // 创建负载均衡器,选择一个从库
        return masterSlaveRule.getLoadBalanceAlgorithm().getDataSource(
                masterSlaveRule.getName(), masterSlaveRule.getMasterDataSourceName(), new ArrayList<>(masterSlaveRule.getSlaveDataSourceNames()));
    }
    
    private boolean isMasterRoute(final SQLStatement sqlStatement) {
        return containsLockSegment(sqlStatement) || !(sqlStatement instanceof SelectStatement) || MasterVisitedManager.isMasterVisited() || HintManager.isMasterRouteOnly();
    }
    
    private boolean containsLockSegment(final SQLStatement sqlStatement) {
        return sqlStatement instanceof SelectStatement && ((SelectStatement) sqlStatement).getLock().isPresent();
    }
}

.

上一篇:DPR Sphere in Cloud


下一篇:分库分表利器——sharding-sphere