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);
}
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);
}
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);
}
}
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);
}
}
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();
}
Aggregations