Search in sources :

Example 16 with Instance

use of com.tencent.polaris.api.pojo.Instance in project polaris-java by polarismesh.

the class WeightedRandomBalance method chooseInstance.

@Override
public Instance chooseInstance(Criteria criteria, ServiceInstances svcInstances) throws PolarisException {
    int totalWeight = svcInstances.getTotalWeight();
    if (totalWeight <= 0) {
        totalWeight = sumTotalWeight(svcInstances);
    }
    if (totalWeight == 0) {
        throw new PolarisException(ErrorCode.INSTANCE_NOT_FOUND, String.format("all instances weight 0 for %s:%s", svcInstances.getNamespace(), svcInstances.getService()));
    }
    // 进行权重区间分配
    List<Instance> instances = svcInstances.getInstances();
    int randomValue = Math.abs(random.nextInt() % totalWeight);
    int start = 0;
    int end = 0;
    for (Instance instance : instances) {
        end = end + instance.getWeight();
        if (randomValue >= start && randomValue < end) {
            return instance;
        }
        start = end;
    }
    // 全都分配不到,则随机获取一个
    return instances.get(totalWeight % instances.size());
}
Also used : PolarisException(com.tencent.polaris.api.exception.PolarisException) Instance(com.tencent.polaris.api.pojo.Instance)

Example 17 with Instance

use of com.tencent.polaris.api.pojo.Instance in project polaris-java by polarismesh.

the class InstancesCircuitBreakTask method cleanInstanceSet.

private void cleanInstanceSet(Map<ResultKey, Instance> instanceSet, Set<ResultKey> allInstances) {
    Set<ResultKey> instIdsToRemove = new HashSet<>();
    for (Map.Entry<ResultKey, Instance> entry : instanceSet.entrySet()) {
        ResultKey resultKey = entry.getKey();
        if (allInstances.contains(resultKey)) {
            instIdsToRemove.add(resultKey);
        } else {
            allInstances.add(resultKey);
        }
    }
    instIdsToRemove.forEach(instanceSet::remove);
}
Also used : Instance(com.tencent.polaris.api.pojo.Instance) HashMap(java.util.HashMap) Map(java.util.Map) ResultKey(com.tencent.polaris.api.plugin.circuitbreaker.CircuitBreakResult.ResultKey) HashSet(java.util.HashSet)

Example 18 with Instance

use of com.tencent.polaris.api.pojo.Instance in project polaris-java by polarismesh.

the class InstancesCircuitBreakTask method run.

@Override
public void run() {
    Map<String, CircuitBreakResult> allResults = new HashMap<>();
    Set<ResultKey> statusChangedInstances = new HashSet<>();
    Collection<Instance> targetInstances = instances;
    if (StringUtils.isNotEmpty(instId)) {
        Instance instance = getInstance();
        if (null != instance) {
            targetInstances = new ArrayList<>();
            targetInstances.add(instance);
        }
    }
    if (CollectionUtils.isEmpty(targetInstances)) {
        return;
    }
    for (CircuitBreaker circuitBreaker : extensions.getCircuitBreakers()) {
        if (StringUtils.isNotBlank(cbName) && !cbName.equals(circuitBreaker.getName())) {
            continue;
        }
        CircuitBreakResult circuitBreakResult = circuitBreaker.checkInstance(targetInstances);
        if (null == circuitBreakResult || circuitBreakResult.isEmptyResult()) {
            continue;
        }
        cleanInstanceSet(circuitBreakResult.getInstancesToOpen(), statusChangedInstances);
        cleanInstanceSet(circuitBreakResult.getInstancesToHalfOpen(), statusChangedInstances);
        cleanInstanceSet(circuitBreakResult.getInstancesToClose(), statusChangedInstances);
        allResults.put(circuitBreaker.getName(), circuitBreakResult);
    }
    ServiceUpdateRequest updateRequest = buildServiceUpdateRequest(serviceKey, allResults);
    if (CollectionUtils.isEmpty(updateRequest.getProperties())) {
        return;
    }
    LOG.info("update cache for circuitbreaker, value is {}", updateRequest);
    extensions.getLocalRegistry().updateInstances(updateRequest);
}
Also used : CircuitBreaker(com.tencent.polaris.api.plugin.circuitbreaker.CircuitBreaker) HashMap(java.util.HashMap) Instance(com.tencent.polaris.api.pojo.Instance) ServiceUpdateRequest(com.tencent.polaris.api.plugin.registry.ServiceUpdateRequest) CircuitBreakResult(com.tencent.polaris.api.plugin.circuitbreaker.CircuitBreakResult) ResultKey(com.tencent.polaris.api.plugin.circuitbreaker.CircuitBreakResult.ResultKey) HashSet(java.util.HashSet)

Example 19 with Instance

use of com.tencent.polaris.api.pojo.Instance in project polaris-java by polarismesh.

the class InstancesCircuitBreakTask method buildInstanceProperty.

@SuppressWarnings("unchecked")
private void buildInstanceProperty(long now, Map<ResultKey, Instance> results, int maxRequestAfterHalfOpen, Map<String, InstanceProperty> instanceProperties, String cbName, CircuitBreakerStatus.Status status) {
    if (MapUtils.isEmpty(results)) {
        return;
    }
    for (Map.Entry<ResultKey, Instance> entry : results.entrySet()) {
        ResultKey resultKey = entry.getKey();
        Instance instance = entry.getValue();
        String instId = resultKey.getInstId();
        InstanceProperty instanceProperty = instanceProperties.get(instId);
        if (null == instanceProperty) {
            Map<String, Object> properties = new HashMap<>();
            properties.put(PROPERTY_CIRCUIT_BREAKER_STATUS, new HashMap<StatusDimension, CircuitBreakerStatus>());
            instanceProperty = new InstanceProperty(instance, properties);
            instanceProperties.put(instId, instanceProperty);
        }
        Map<StatusDimension, CircuitBreakerStatus> statusMap = (Map<StatusDimension, CircuitBreakerStatus>) instanceProperty.getProperties().get(PROPERTY_CIRCUIT_BREAKER_STATUS);
        statusMap.put(resultKey.getStatusDimension(), new CircuitBreakerStatus(cbName, status, now));
    }
}
Also used : Instance(com.tencent.polaris.api.pojo.Instance) HashMap(java.util.HashMap) InstanceProperty(com.tencent.polaris.api.plugin.registry.InstanceProperty) StatusDimension(com.tencent.polaris.api.pojo.StatusDimension) CircuitBreakerStatus(com.tencent.polaris.api.pojo.CircuitBreakerStatus) HashMap(java.util.HashMap) Map(java.util.Map) ResultKey(com.tencent.polaris.api.plugin.circuitbreaker.CircuitBreakResult.ResultKey)

Example 20 with Instance

use of com.tencent.polaris.api.pojo.Instance in project polaris-java by polarismesh.

the class CircuitBreakExample method main.

public static void main(String[] args) throws Throwable {
    InitResult initResult = CircuitBreakExampleUtils.initConfiguration(args);
    // 由于需要用到多个API对象,因此可以使用SDKContext使得多个API对象的资源都可以共享
    try (SDKContext sdkContext = SDKContext.initContext()) {
        ProviderAPI providerAPI = DiscoveryAPIFactory.createProviderAPIByContext(sdkContext);
        // 1. 先注册服务实例
        registerInstances(providerAPI, initResult);
        // 2. 获取可用的服务实例列表
        ConsumerAPI consumerAPI = DiscoveryAPIFactory.createConsumerAPIByContext(sdkContext);
        Instance[] availableInstances = getAvailableInstances(consumerAPI, initResult);
        System.out.println("available instances count is " + availableInstances.length);
        // 3. 针对某个服务实例上报调用结果失败,默认连续10次失败,或者1分钟错误率50%,就会对实例进行熔断
        Instance targetInstance = availableInstances[0];
        System.out.printf("target instance is %s:%d%n", targetInstance.getHost(), targetInstance.getPort());
        for (int i = 0; i < 120000; i++) {
            // 这里要进行服务调用,用户可以写自己的服务调用代码
            for (Instance instance : availableInstances) {
                ServiceCallResult serviceCallResult = new ServiceCallResult();
                serviceCallResult.setInstance(targetInstance);
                serviceCallResult.setMethod("echo");
                if (instance.getHost().equals(targetInstance.getHost()) && instance.getPort() == targetInstance.getPort()) {
                    serviceCallResult.setRetStatus(RetStatus.RetFail);
                    serviceCallResult.setDelay(2000);
                } else {
                    serviceCallResult.setRetStatus(RetStatus.RetSuccess);
                    serviceCallResult.setDelay(20);
                }
                consumerAPI.updateServiceCallResult(serviceCallResult);
            }
            System.out.printf("report call result %d%n", i);
            CircuitBreakExampleUtils.doSleep(500);
        }
        // 4. 判断服务实例是否还在可用列表中,已经熔断的实例是不会再次返回
        availableInstances = getAvailableInstances(consumerAPI, initResult);
        System.out.println("available instances count is " + availableInstances.length);
        for (Instance instance : availableInstances) {
            System.out.printf("available instance is %s:%d%n", instance.getHost(), instance.getPort());
        }
        // 4. 反注册服务实例
        System.out.println("start to deregister instances");
        deregisterInstances(providerAPI, initResult);
    }
}
Also used : SDKContext(com.tencent.polaris.client.api.SDKContext) ProviderAPI(com.tencent.polaris.api.core.ProviderAPI) InitResult(com.tencent.polaris.circuitbreak.example.CircuitBreakExampleUtils.InitResult) ServiceCallResult(com.tencent.polaris.api.rpc.ServiceCallResult) Instance(com.tencent.polaris.api.pojo.Instance) ConsumerAPI(com.tencent.polaris.api.core.ConsumerAPI)

Aggregations

Instance (com.tencent.polaris.api.pojo.Instance)53 ArrayList (java.util.ArrayList)15 InstancesResponse (com.tencent.polaris.api.rpc.InstancesResponse)14 ServiceInstances (com.tencent.polaris.api.pojo.ServiceInstances)12 Server (com.netflix.loadbalancer.Server)9 ConsumerAPI (com.tencent.polaris.api.core.ConsumerAPI)9 PolarisServer (com.tencent.cloud.common.pojo.PolarisServer)6 Configuration (com.tencent.polaris.api.config.Configuration)6 GetOneInstanceRequest (com.tencent.polaris.api.rpc.GetOneInstanceRequest)6 HashMap (java.util.HashMap)6 DefaultServiceInstances (com.tencent.polaris.api.pojo.DefaultServiceInstances)5 ServiceKey (com.tencent.polaris.api.pojo.ServiceKey)5 ServiceCallResult (com.tencent.polaris.api.rpc.ServiceCallResult)5 HashSet (java.util.HashSet)5 LinkedList (java.util.LinkedList)5 Map (java.util.Map)5 PolarisException (com.tencent.polaris.api.exception.PolarisException)4 ResultKey (com.tencent.polaris.api.plugin.circuitbreaker.CircuitBreakResult.ResultKey)4 DefaultInstance (com.tencent.polaris.api.pojo.DefaultInstance)4 StatusDimension (com.tencent.polaris.api.pojo.StatusDimension)4