Search in sources :

Example 1 with MetadataFailoverType

use of com.tencent.polaris.api.rpc.MetadataFailoverType in project polaris-java by polarismesh.

the class MetadataRouter method router.

@Override
public RouteResult router(RouteInfo routeInfo, ServiceInstances instances) throws PolarisException {
    FailOverType failOverType = config.getMetadataFailOverType();
    Map<String, String> svcMetadata = instances.getMetadata();
    if (MapUtils.isNotEmpty(svcMetadata)) {
        if (svcMetadata.containsKey(KEY_METADATA_FAILOVER_TYPE)) {
            String value = svcMetadata.get(KEY_METADATA_FAILOVER_TYPE);
            if (valueToFailoverType.containsKey(value)) {
                failOverType = valueToFailoverType.get(value);
            }
        }
    }
    MetadataFailoverType metadataFailoverType = routeInfo.getMetadataFailoverType();
    if (null != metadataFailoverType) {
        failOverType = inputToFailoverType.get(metadataFailoverType);
    }
    boolean availableInsFlag;
    Map<String, String> reqMetadata = routeInfo.getDestService().getMetadata();
    List<Instance> instanceList = new ArrayList<>();
    for (Instance ins : instances.getInstances()) {
        availableInsFlag = true;
        // 要满足请求中的metadata K-V全部存在于实例的metadata中
        for (Map.Entry<String, String> entry : reqMetadata.entrySet()) {
            if (ins.getMetadata().containsKey(entry.getKey()) && ins.getMetadata().get(entry.getKey()).equals(entry.getValue())) {
                continue;
            }
            availableInsFlag = false;
            break;
        }
        if (availableInsFlag) {
            instanceList.add(ins);
        }
    }
    if (!CollectionUtils.isEmpty(instanceList)) {
        return new RouteResult(instanceList, RouteResult.State.Next);
    }
    switch(failOverType) {
        case all:
            return new RouteResult(instances.getInstances(), RouteResult.State.Next);
        case others:
            return new RouteResult(addNotContainKeyIns(instances, reqMetadata), RouteResult.State.Next);
        default:
            // 默认不降级
            throw new PolarisException(ErrorCode.METADATA_MISMATCH, String.format("can not find any instance by service %s", routeInfo.getDestService()));
    }
}
Also used : PolarisException(com.tencent.polaris.api.exception.PolarisException) Instance(com.tencent.polaris.api.pojo.Instance) RouteResult(com.tencent.polaris.api.plugin.route.RouteResult) MetadataFailoverType(com.tencent.polaris.api.rpc.MetadataFailoverType) ArrayList(java.util.ArrayList) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

PolarisException (com.tencent.polaris.api.exception.PolarisException)1 RouteResult (com.tencent.polaris.api.plugin.route.RouteResult)1 Instance (com.tencent.polaris.api.pojo.Instance)1 MetadataFailoverType (com.tencent.polaris.api.rpc.MetadataFailoverType)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1