Search in sources :

Example 1 with ServiceInfo

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

the class BaseFlow method commonGetOneInstance.

/**
 * 通用获取单个服务实例的方法,用于SDK内部调用
 *
 * @param extensions 插件上下文
 * @param serviceKey 服务信息
 * @param coreRouterNames 核心路由插件链
 * @param lbPolicy 负载均衡策略
 * @param protocol 协议信息
 * @param hashKey 一致性hash的key
 * @return 过滤后的实例
 */
public static Instance commonGetOneInstance(Extensions extensions, ServiceKey serviceKey, List<String> coreRouterNames, String lbPolicy, String protocol, String hashKey) {
    ServiceEventKey svcEventKey = new ServiceEventKey(serviceKey, EventType.INSTANCE);
    LOG.info("[ConnectionManager]start to discover service {}", svcEventKey);
    DefaultServiceEventKeysProvider provider = new DefaultServiceEventKeysProvider();
    provider.setSvcEventKey(svcEventKey);
    // 为性能考虑,优先使用本地缓存
    provider.setUseCache(true);
    FlowControlParam flowControlParam = new DefaultFlowControlParam();
    APIConfig apiConfig = extensions.getConfiguration().getGlobal().getAPI();
    flowControlParam.setTimeoutMs(apiConfig.getTimeout());
    flowControlParam.setMaxRetry(apiConfig.getMaxRetryTimes());
    flowControlParam.setRetryIntervalMs(apiConfig.getRetryInterval());
    // 执行服务路由
    ServiceInfo dstSvcInfo = new ServiceInfo();
    Map<String, String> metadata = new HashMap<>();
    metadata.put("protocol", protocol);
    dstSvcInfo.setMetadata(metadata);
    RouteInfo routeInfo = new RouteInfo(null, null, dstSvcInfo, null, "");
    ResourcesResponse resourcesResponse = BaseFlow.syncGetResources(extensions, false, provider, flowControlParam);
    LOG.info("[ConnectionManager]success to discover service {}", svcEventKey);
    ServiceInstances serviceInstances = resourcesResponse.getServiceInstances(svcEventKey);
    RouterChainGroup sysRouterChainGroup = extensions.getSysRouterChainGroup();
    List<ServiceRouter> coreRouters = Extensions.loadServiceRouters(coreRouterNames, extensions.getPlugins(), false);
    RouterChainGroup routerChainGroup = new DefaultRouterChainGroup(sysRouterChainGroup.getBeforeRouters(), coreRouters, sysRouterChainGroup.getAfterRouters());
    ServiceInstances instancesAfterRoute = BaseFlow.processServiceRouters(routeInfo, serviceInstances, routerChainGroup);
    // 执行负载均衡
    LoadBalancer loadBalancer = (LoadBalancer) extensions.getPlugins().getPlugin(PluginTypes.LOAD_BALANCER.getBaseType(), lbPolicy);
    Criteria criteria = new Criteria();
    criteria.setHashKey(hashKey);
    return BaseFlow.processLoadBalance(loadBalancer, criteria, instancesAfterRoute);
}
Also used : ServiceRouter(com.tencent.polaris.api.plugin.route.ServiceRouter) DefaultServiceEventKeysProvider(com.tencent.polaris.api.pojo.DefaultServiceEventKeysProvider) HashMap(java.util.HashMap) LoadBalancer(com.tencent.polaris.api.plugin.loadbalance.LoadBalancer) Criteria(com.tencent.polaris.api.rpc.Criteria) ServiceInfo(com.tencent.polaris.api.pojo.ServiceInfo) ServiceInstances(com.tencent.polaris.api.pojo.ServiceInstances) APIConfig(com.tencent.polaris.api.config.global.APIConfig) DefaultRouterChainGroup(com.tencent.polaris.api.plugin.compose.DefaultRouterChainGroup) RouterChainGroup(com.tencent.polaris.api.plugin.compose.RouterChainGroup) ServiceEventKey(com.tencent.polaris.api.pojo.ServiceEventKey) RouteInfo(com.tencent.polaris.api.plugin.route.RouteInfo) DefaultRouterChainGroup(com.tencent.polaris.api.plugin.compose.DefaultRouterChainGroup)

Example 2 with ServiceInfo

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

the class CompositeServiceUpdateTask method notifyServerEvent.

@Override
public boolean notifyServerEvent(ServerEvent serverEvent) {
    taskStatus.compareAndSet(Status.RUNNING, Status.READY);
    lastUpdateTime.set(System.currentTimeMillis());
    try {
        if (serverEvent.getValue() instanceof DiscoverResponse) {
            DiscoverResponse discoverResponse = (DiscoverResponse) serverEvent.getValue();
            DiscoverResponse.Builder newDiscoverResponseBuilder = DiscoverResponse.newBuilder().mergeFrom(discoverResponse);
            CompositeConnector connector = (CompositeConnector) serverConnector;
            if (EventType.INSTANCE.equals(serviceEventKey.getEventType())) {
                // Get instance information list except polaris.
                List<DefaultInstance> extendInstanceList = new ArrayList<>();
                for (DestroyableServerConnector sc : connector.getServerConnectors()) {
                    if (!DefaultPlugins.SERVER_CONNECTOR_GRPC.equals(sc.getName())) {
                        List<DefaultInstance> instanceList = sc.syncGetServiceInstances(this);
                        if (extendInstanceList.isEmpty()) {
                            extendInstanceList.addAll(instanceList);
                        } else {
                        // TODO 多数据源合并去重
                        }
                    }
                }
                // Merge instance information list
                List<Instance> polarisInstanceList = discoverResponse.getInstancesList();
                for (DefaultInstance i : extendInstanceList) {
                    boolean needAdd = true;
                    for (Instance j : polarisInstanceList) {
                        if (i.getHost().equals(j.getHost().getValue()) && i.getPort() == j.getPort().getValue()) {
                            needAdd = false;
                            break;
                        }
                    }
                    if (needAdd) {
                        Instance.Builder instanceBuilder = Instance.newBuilder().setNamespace(StringValue.of(serviceEventKey.getNamespace())).setService(StringValue.of(i.getService())).setHost(StringValue.of(i.getHost())).setPort(UInt32Value.of(i.getPort())).setHealthy(BoolValue.of(true));
                        if (StringUtils.isNotBlank(i.getId())) {
                            instanceBuilder.setId(StringValue.of(i.getId()));
                        }
                        newDiscoverResponseBuilder.addInstances(instanceBuilder.build());
                    }
                }
                if (!newDiscoverResponseBuilder.getInstancesList().isEmpty()) {
                    serverEvent.setError(null);
                }
            } else if (EventType.SERVICE.equals(serviceEventKey.getEventType())) {
                // Get instance information list except polaris.
                List<ServiceInfo> extendServiceList = new ArrayList<>();
                for (DestroyableServerConnector sc : connector.getServerConnectors()) {
                    if (!DefaultPlugins.SERVER_CONNECTOR_GRPC.equals(sc.getName())) {
                        Services services = sc.syncGetServices(this);
                        if (extendServiceList.isEmpty()) {
                            extendServiceList.addAll(services.getServices());
                        } else {
                        // TODO 多数据源合并去重
                        }
                    }
                }
                // Merge service information list
                List<Service> polarisServiceList = discoverResponse.getServicesList();
                for (ServiceInfo i : extendServiceList) {
                    boolean needAdd = true;
                    for (Service j : polarisServiceList) {
                        if (i.getService().equals(j.getName().getValue())) {
                            needAdd = false;
                            break;
                        }
                    }
                    if (needAdd) {
                        Service service = Service.newBuilder().setNamespace(StringValue.of(serviceEventKey.getNamespace())).setName(StringValue.of(i.getService())).build();
                        newDiscoverResponseBuilder.addServices(service);
                    }
                }
                if (!newDiscoverResponseBuilder.getServicesList().isEmpty()) {
                    serverEvent.setError(null);
                }
            }
            serverEvent.setValue(newDiscoverResponseBuilder.build());
        }
    } catch (PolarisException e) {
        LOG.error("Merge other server response failed.", e);
        serverEvent.setError(e);
    } catch (Throwable throwable) {
        LOG.error("Merge other server response failed.", throwable);
        serverEvent.setError(new PolarisException(ErrorCode.INTERNAL_ERROR));
    }
    if (null == serverEvent.getError()) {
        successUpdates.addAndGet(1);
    }
    return getEventHandler().onEventUpdate(serverEvent);
}
Also used : DefaultInstance(com.tencent.polaris.api.pojo.DefaultInstance) Instance(com.tencent.polaris.client.pb.ServiceProto.Instance) ArrayList(java.util.ArrayList) Service(com.tencent.polaris.client.pb.ServiceProto.Service) DiscoverResponse(com.tencent.polaris.client.pb.ResponseProto.DiscoverResponse) ServiceInfo(com.tencent.polaris.api.pojo.ServiceInfo) PolarisException(com.tencent.polaris.api.exception.PolarisException) Services(com.tencent.polaris.api.pojo.Services) DefaultInstance(com.tencent.polaris.api.pojo.DefaultInstance) ArrayList(java.util.ArrayList) List(java.util.List) DestroyableServerConnector(com.tencent.polaris.plugins.connector.common.DestroyableServerConnector)

Example 3 with ServiceInfo

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

the class ServiceDynamicRuleTest method testServiceDynamicRule.

@Test
public void testServiceDynamicRule() {
    GetInstancesRequest getInstancesRequest = new GetInstancesRequest();
    getInstancesRequest.setNamespace(NAMESPACE_PRODUCTION);
    getInstancesRequest.setService(RULE_ROUTER_SERVICE);
    Map<String, String> map = new HashMap<>();
    map.put("uid", "144115217417489762");
    ServiceInfo serviceInfo = new ServiceInfo();
    serviceInfo.setNamespace(NAMESPACE_PRODUCTION);
    serviceInfo.setService(RULE_ROUTER_SERVICE);
    serviceInfo.setMetadata(map);
    // 设置主调方服务信息 即 Metadata等规则信息
    getInstancesRequest.setServiceInfo(serviceInfo);
    Configuration configuration = TestUtils.configWithEnvAddress();
    try (ConsumerAPI consumerAPI = DiscoveryAPIFactory.createConsumerAPIByConfig(configuration)) {
        InstancesResponse oneInstance = consumerAPI.getInstances(getInstancesRequest);
        Assert.assertEquals(MATCH_META_COUNT, oneInstance.getInstances().length);
    }
}
Also used : ServiceInfo(com.tencent.polaris.api.pojo.ServiceInfo) Configuration(com.tencent.polaris.api.config.Configuration) GetInstancesRequest(com.tencent.polaris.api.rpc.GetInstancesRequest) HashMap(java.util.HashMap) MatchString(com.tencent.polaris.client.pb.ModelProto.MatchString) ConsumerAPI(com.tencent.polaris.api.core.ConsumerAPI) InstancesResponse(com.tencent.polaris.api.rpc.InstancesResponse) Test(org.junit.Test)

Example 4 with ServiceInfo

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

the class GetServicesExample method main.

public static void main(String[] args) throws Exception {
    InitResult initResult = ExampleUtils.initConsumerConfiguration(args, true);
    String namespace = initResult.getNamespace();
    try (ConsumerAPI consumerAPI = ExampleUtils.createConsumerAPI(initResult.getConfig())) {
        System.out.println("namespace " + namespace);
        GetServicesRequest request = new GetServicesRequest();
        request.setNamespace(namespace);
        ServicesResponse response = consumerAPI.getServices(request);
        List<ServiceInfo> services = response.getServices();
        System.out.println("services count is " + services.size());
        System.out.println("print all service " + services);
        request = new GetServicesRequest();
        request.setNamespace(namespace);
        response = consumerAPI.getServices(request);
        services = response.getServices();
        System.out.println("services count is " + services.size());
        System.out.println("print all service " + services);
    }
}
Also used : ServiceInfo(com.tencent.polaris.api.pojo.ServiceInfo) InitResult(com.tencent.polaris.discovery.example.utils.ExampleUtils.InitResult) ServicesResponse(com.tencent.polaris.api.rpc.ServicesResponse) ConsumerAPI(com.tencent.polaris.api.core.ConsumerAPI) GetServicesRequest(com.tencent.polaris.api.rpc.GetServicesRequest)

Example 5 with ServiceInfo

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

the class PolarisServiceRouter method getInstances.

/**
 * 利用ConsumerAPI进行路由
 *
 * @param service
 * @return
 */
public static ServiceInstances getInstances(String service) {
    LogUtils.logInvoke(PolarisServiceRouter.class, "getInstances");
    PolarisAgentProperties polarisAgentProperties = PolarisAgentPropertiesFactory.getPolarisAgentProperties();
    String namespace = polarisAgentProperties.getNamespace();
    GetInstancesRequest getInstancesRequest = new GetInstancesRequest();
    getInstancesRequest.setNamespace(namespace);
    getInstancesRequest.setService(service);
    String srcNamespace = polarisAgentProperties.getNamespace();
    String srcService = polarisAgentProperties.getService();
    if (StringUtils.isNotBlank(srcNamespace) || StringUtils.isNotBlank(srcService)) {
        ServiceInfo sourceService = new ServiceInfo();
        sourceService.setNamespace(srcNamespace);
        sourceService.setService(srcService);
        getInstancesRequest.setServiceInfo(sourceService);
    }
    InstancesResponse response = PolarisAPIFactory.getConsumerApi().getInstances(getInstancesRequest);
    LOGGER.info("success to route by Polaris with instance size:{}", response.getInstances().length);
    return response.toServiceInstances();
}
Also used : ServiceInfo(com.tencent.polaris.api.pojo.ServiceInfo) PolarisAgentProperties(cn.polarismesh.agent.core.spring.cloud.context.PolarisAgentProperties) GetInstancesRequest(com.tencent.polaris.api.rpc.GetInstancesRequest) InstancesResponse(com.tencent.polaris.api.rpc.InstancesResponse)

Aggregations

ServiceInfo (com.tencent.polaris.api.pojo.ServiceInfo)16 InstancesResponse (com.tencent.polaris.api.rpc.InstancesResponse)5 ProcessRoutersRequest (com.tencent.polaris.router.api.rpc.ProcessRoutersRequest)5 ArrayList (java.util.ArrayList)5 ServiceInstances (com.tencent.polaris.api.pojo.ServiceInstances)4 GetInstancesRequest (com.tencent.polaris.api.rpc.GetInstancesRequest)4 ProcessRoutersResponse (com.tencent.polaris.router.api.rpc.ProcessRoutersResponse)4 HashMap (java.util.HashMap)4 PolarisAgentProperties (cn.polarismesh.agent.core.spring.cloud.context.PolarisAgentProperties)3 ConsumerAPI (com.tencent.polaris.api.core.ConsumerAPI)3 DefaultInstance (com.tencent.polaris.api.pojo.DefaultInstance)3 ServiceKey (com.tencent.polaris.api.pojo.ServiceKey)3 DefaultServiceInstances (com.tencent.polaris.api.pojo.DefaultServiceInstances)2 Instance (com.tencent.polaris.api.pojo.Instance)2 ServiceEventKey (com.tencent.polaris.api.pojo.ServiceEventKey)2 Services (com.tencent.polaris.api.pojo.Services)2 ServicesByProto (com.tencent.polaris.client.pojo.ServicesByProto)2 Test (org.junit.Test)2 PolarisServiceInstance (cn.polarismesh.agent.core.spring.cloud.discovery.PolarisServiceInstance)1 ConsulException (com.ecwid.consul.ConsulException)1