Java源码示例:com.netflix.niws.loadbalancer.DiscoveryEnabledServer
示例1
protected List<Server> getUnUpServerList(String serviceId, List<InstanceStatus> instanceStatuses) {
Application application = eurekaClient.getApplication(serviceId);
if (Objects.isNull(application)) {
return null;
}
return application.getInstancesAsIsFromEureka().stream()
.filter(instanceInfo -> instanceStatuses.contains(EurekaInstatnceTransformer.toGrayInstanceStatus(instanceInfo.getStatus())))
.map(instanceInfo -> {
DiscoveryEnabledServer server = new DiscoveryEnabledServer(instanceInfo, false);
String zone = server.getInstanceInfo().getMetadata().get("zone");
if (StringUtils.isNotEmpty(zone)) {
server.setZone(zone);
}
return server;
})
.collect(Collectors.toList());
}
示例2
/**
* This method stores the instance info of chosen instance in the RequestContext for later usage, for
* example by authentication logic
*/
@Override
public Server chooseServer(Object key) {
Server server = super.chooseServer(key);
if (server == null) {
return null;
}
if (server instanceof DiscoveryEnabledServer) {
RequestContextUtils.setInstanceInfo(((DiscoveryEnabledServer) server).getInstanceInfo());
RequestContextUtils.addDebugInfo("Load Balancer chooses: " + ((DiscoveryEnabledServer) server).getInstanceInfo());
} else {
throw new IllegalStateException("Unexpected error, please contact Broadcom support");
}
return server;
}
示例3
/**
* This method stores the instance info of chosen instance in the RequestContext for later usage, for
* example by authentication logic.
*/
@Override
public Server chooseServer(Object key) {
Server server = new DiscoveryEnabledServer(applicationRegistry.getInstanceInfo(), true);
server.setAlive(true);
server.setReadyToServe(true);
if (server instanceof DiscoveryEnabledServer) {
RequestContextUtils.setInstanceInfo(((DiscoveryEnabledServer) server).getInstanceInfo());
RequestContextUtils.addDebugInfo("Load Balancer chooses: " + ((DiscoveryEnabledServer) server).getInstanceInfo());
} else {
throw new IllegalStateException("Unexpected error, please contact Broadcom support");
}
return server;
}
示例4
/**
* {@inheritDoc}
*/
@Override
protected boolean doApply(DiscoveryEnabledServer server) {
String metadataKey = current().get(dynamicEntryKey);
Map<String, String> metadata = server.getInstanceInfo().getMetadata();
if (metadataKey != null) {
String expected = current().get(metadataKey);
String actual = metadata.get(metadataKey);
boolean accept = (expected == null && actual == null) || (expected != null && expected.equals(actual));
log.trace("Expected [{}={}] vs {}:{}{} => {}",
metadataKey,
expected,
server.getHostPort(),
server.getMetaInfo().getAppName(),
metadata,
accept);
return accept;
} else {
log.trace("[{}] not defined! : {}{} => %b",
dynamicEntryKey,
server.getHostPort(),
metadata,
matchIfMissing);
return matchIfMissing;
}
}
示例5
/**
* {@inheritDoc}
*/
@Override
protected boolean doApply(DiscoveryEnabledServer server) {
String expected = current().get(metadataKey);
Map<String, String> metadata = server.getInstanceInfo().getMetadata();
String actual = metadata.get(metadataKey);
boolean accept = (expected == null && actual == null) || (expected != null && expected.equals(actual));
log.trace("Expected {}=[{}] vs {}:{}{} => {}",
metadataKey,
expected,
server.getHostPort(),
server.getMetaInfo().getAppName(),
metadata,
accept);
return accept;
}
示例6
private static DiscoveryEnabledServer createDiscoveryEnabledServer(double load) {
Map<String, String> metadata = new HashMap<>();
ServerLoadStatus serverLoad = new ServerLoadStatus();
serverLoad.calculateSystemInfo();
serverLoad.setSystemLoadAverage(load);
serverLoad.setOsName(serverLoad.getOsName() + "-" + load);
String serverLoadJson = JsonUtil.toJson(serverLoad);
metadata.put(Constants.EUREKA_METADATA_SERVERLOAD, serverLoadJson);
InstanceInfo instanceInfo1 = InstanceInfo.Builder.newBuilder().setHostName("host" + load)
.setAppName("app" + load).setMetadata(metadata).build();
DiscoveryEnabledServer server = new DiscoveryEnabledServer(instanceInfo1, false);
return server;
}
示例7
protected RestClient getRestClient() throws ZuulException {
Application application = DiscoveryManager.getInstance().getDiscoveryClient().getApplication(serviceName);
if (application == null) {
throw new ZuulException( "Service-NotFoud",HttpServletResponse.SC_NOT_FOUND, serviceName + "服务未找到");
}
List<DiscoveryEnabledServer> instances = Lists.newArrayList();
for (InstanceInfo info : application.getInstances()) {
if (info.getStatus() == InstanceStatus.UP) {
instances.add(new DiscoveryEnabledServer(info, false, false));
}
}
RestClient client = (RestClient) ClientFactory.getNamedClient(serviceName);
ZoneAwareLoadBalancer loadbalancer = (ZoneAwareLoadBalancer) client.getLoadBalancer();
// //loadbalancer.setServersList(instances);
// IRule rule = new RandomRule();
// int ruleLoad = ZuulCommandHelper.getLoadBalanceRule(commandGroup, commandKey);
// if (ruleLoad == 2) {
// rule = new ClientConfigEnabledRoundRobinRule();
// } else if (ruleLoad == 3) {
// rule=new AvailabilityFilteringRule();
// } else if (ruleLoad == 3) {
// rule=new ZoneAvoidanceRule();
// } else if (ruleLoad == 4) {
// rule=new RetryRule();
// } else if (ruleLoad == 5) {
// rule=new RoundRobinRule();
// }else if (ruleLoad == 6) {
// rule=new ResponseTimeWeightedRule();
// }else if (ruleLoad == 7) {
// rule=new WeightedResponseTimeRule();
// }
// loadbalancer.setRule(rule);
// client.setLoadBalancer(loadbalancer);
return client;
}
示例8
@Override
public AbstractServerPredicate getPredicate() {
return new AbstractServerPredicate() {
@Override
public boolean apply(PredicateKey predicateKey) {
String targetVersion = RibbonVersionHolder.getContext();
RibbonVersionHolder.clearContext();
if (StrUtil.isBlank(targetVersion)) {
log.debug("客户端未配置目标版本直接路由");
return true;
}
DiscoveryEnabledServer server = (DiscoveryEnabledServer) predicateKey.getServer();
final Map<String, String> metadata = server.getInstanceInfo().getMetadata();
if (StrUtil.isBlank(metadata.get(SecurityConstants.VERSION))) {
log.debug("当前微服务{} 未配置版本直接路由");
return true;
}
if (metadata.get(SecurityConstants.VERSION).equals(targetVersion)) {
return true;
} else {
log.debug("当前微服务{} 版本为{},目标版本{} 匹配失败", server.getInstanceInfo().getAppName()
, metadata.get(SecurityConstants.VERSION), targetVersion);
return false;
}
}
};
}
示例9
@Test
void givenServerList_whenChooseServer_thenSetChosenInstanceInfoToRequestContext() {
InstanceInfo info = InstanceInfo.Builder.newBuilder()
.setAppName("appname")
.setInstanceId("instance")
.build();
underTest.addServer(new DiscoveryEnabledServer(info, true));
underTest.chooseServer("instance");
RequestContext context = RequestContext.getCurrentContext();
assertThat(context.get(ApimlLoadBalancer.LOADBALANCED_INSTANCE_INFO_KEY), is(info));
}
示例10
/**
* {@inheritDoc}
*/
@Override
protected boolean doApply(DiscoveryEnabledServer server) {
Set<Entry<String, String>> expected = current().entrySet();
Map<String, String> actual = server.getInstanceInfo().getMetadata();
boolean accept = actual.entrySet().containsAll(expected);
log.trace("Expected {} vs {}:{}{} => {}",
expected,
server.getHostPort(),
server.getMetaInfo().getAppName(),
actual,
accept);
return accept;
}
示例11
/**
* {@inheritDoc}
*/
@Override
protected boolean doApply(DiscoveryEnabledServer server) {
Map<String, String> metadata = server.getInstanceInfo().getMetadata();
String actual = metadata.get(entryKey);
boolean accept = entryValue.equals(actual);
log.trace("Expected [{}={}] vs {}:{}{} => {}",
entryKey,
entryValue,
server.getHostPort(),
server.getMetaInfo().getAppName(),
metadata,
accept);
return accept;
}
示例12
/**
* {@inheritDoc}
*/
@Override
@SuppressFBWarnings("BC_UNCONFIRMED_CAST_OF_RETURN_VALUE")
protected boolean doApply(PredicateKey input) {
return input.getServer() instanceof DiscoveryEnabledServer
&& doApply((DiscoveryEnabledServer) input.getServer());
}
示例13
/**
* {@inheritDoc}
*/
@Override
protected boolean doApply(DiscoveryEnabledServer server) {
String actual = server.getInstanceInfo().getInstanceId();
boolean accept = expectedInstanceId.equals(actual);
log.trace("Expected [{}] vs {}:{}[{}] => {}",
expectedInstanceId,
server.getHostPort(),
server.getMetaInfo().getAppName(),
actual,
accept);
return accept;
}
示例14
public DiscoveryEnabledServer createServer(String zone) {
DiscoveryEnabledServer server = new DiscoveryEnabledServer(InstanceInfo.Builder.newBuilder()
.setAppName(TestApplicationResource.SERVICE_ID)
.setHostName("127.0.0.1")
.setMetadata(new HashMap<>())
.build(), false);
server.setZone(zone);
server.setAlive(true);
server.setReadyToServe(true);
return server;
}
示例15
@Override
public boolean apply(PredicateKey input) {
if(!DiscoveryEnabledServer.class.isInstance(input.getServer())){
return false;
}
DiscoveryEnabledServer server = (DiscoveryEnabledServer) input.getServer();
Map<String, String> metaData = server.getInstanceInfo().getMetadata();
return matchMetaData(metaData);
}
示例16
@Override
public boolean apply(PredicateKey input) {
if(!DiscoveryEnabledServer.class.isInstance(input.getServer())){
return false;
}
DiscoveryEnabledServer server = (DiscoveryEnabledServer) input.getServer();
Map<String, String> metaData = server.getInstanceInfo().getMetadata();
return matchMetaData(metaData);
}
示例17
/**
* {@inheritDoc}
*/
@Override
public boolean apply(@Nullable PredicateKey input) {
return input != null
&& input.getServer() instanceof DiscoveryEnabledServer
&& apply((DiscoveryEnabledServer) input.getServer());
}
示例18
/**
* {@inheritDoc}
*/
@Override
protected boolean apply(DiscoveryEnabledServer server) {
final RibbonFilterContext context = RibbonFilterContextHolder.getCurrentContext();
final Set<Map.Entry<String, String>> attributes = Collections.unmodifiableSet(context.getAttributes().entrySet());
final Map<String, String> metadata = server.getInstanceInfo().getMetadata();
return metadata.entrySet().containsAll(attributes);
}
示例19
@SuppressWarnings("unchecked")
public static <T extends Server> List<T> servers(InstanceInfo... instanceInfos) {
final List<T> result = new ArrayList<>();
for (InstanceInfo info : instanceInfos) {
result.add((T) new DiscoveryEnabledServer(info, false));
}
return result;
}
示例20
@Bean
public ServerList<?> ribbonServerList() {
Map<String, String> metadata = new HashMap<>();
metadata.put("version", "1.0");
metadata.put("variant", "A");
InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder()
.setAppName("local")
.setHostName("localhost")
.setPort(8761)
.setMetadata(metadata)
.build();
return new StaticServerList<>(Arrays.asList(new DiscoveryEnabledServer(instanceInfo, false)));
}
示例21
@Test
public void testLoadBalancerHappyCase() throws Exception {
Assert.assertNotEquals("the two test server list counts should be different",
secondServerListSize, initialServerListSize);
DynamicServerListLoadBalancer<DiscoveryEnabledServer> lb = null;
try {
Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>();
eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture));
PowerMock.replay(DiscoveryClient.class);
PowerMock.replay(eurekaClientMock);
// actual testing
// initial creation and loading of the first serverlist
lb = new DynamicServerListLoadBalancer<DiscoveryEnabledServer>(
config,
new AvailabilityFilteringRule(),
new DummyPing(),
new DiscoveryEnabledNIWSServerList(vipAddress, eurekaClientProvider),
new ZoneAffinityServerListFilter<DiscoveryEnabledServer>(),
new EurekaNotificationServerListUpdater(eurekaClientProvider)
);
Assert.assertEquals(initialServerListSize, lb.getServerCount(false));
// trigger an eureka CacheRefreshEvent
eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent());
Assert.assertTrue(verifyFinalServerListCount(secondServerListSize, lb));
} finally {
if (lb != null) {
lb.shutdown();
PowerMock.verify(eurekaClientMock);
PowerMock.verify(DiscoveryClient.class);
}
}
}
示例22
@Override
public String getIpAddrFromServer(Server server) {
if (server instanceof DiscoveryEnabledServer) {
DiscoveryEnabledServer discoveryServer = (DiscoveryEnabledServer) server;
if (discoveryServer.getInstanceInfo() != null) {
String ip = discoveryServer.getInstanceInfo().getIPAddr();
if (!Strings.isNullOrEmpty(ip)) {
return ip;
}
}
}
return null;
}
示例23
@VisibleForTesting
static InstanceInfo deriveInstanceInfoInternal(Server chosenServer) {
if (chosenServer instanceof DiscoveryEnabledServer) {
DiscoveryEnabledServer discoveryServer = (DiscoveryEnabledServer) chosenServer;
return discoveryServer.getInstanceInfo();
} else {
return new InstanceInfo(
/* instanceId= */ chosenServer.getId(),
/* appName= */ null,
/* appGroupName= */ null,
/* ipAddr= */ chosenServer.getHost(),
/* sid= */ chosenServer.getId(),
/* port= */ null,
/* securePort= */ null,
/* homePageUrl= */ null,
/* statusPageUrl= */ null,
/* healthCheckUrl= */ null,
/* secureHealthCheckUrl= */ null,
/* vipAddress= */ null,
/* secureVipAddress= */ null,
/* countryId= */ 0,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null);
}
}
示例24
@VisibleForTesting
static SocketAddress pickAddressInternal(Server chosenServer, @Nullable String connPoolConfigOriginName) {
String rawHost;
int port;
if (chosenServer instanceof DiscoveryEnabledServer) {
DiscoveryEnabledServer discoveryServer = (DiscoveryEnabledServer) chosenServer;
// Configuration for whether to use IP address or host has already been applied in the
// DiscoveryEnabledServer constructor.
rawHost = discoveryServer.getHost();
port = discoveryServer.getPort();
} else {
// create mock instance info for non-discovery instances
rawHost = chosenServer.getHost();
port = chosenServer.getPort();
}
InetSocketAddress serverAddr;
try {
InetAddress ipAddr = InetAddresses.forString(rawHost);
serverAddr = new InetSocketAddress(ipAddr, port);
} catch (IllegalArgumentException e1) {
LOG.warn("NettyClientConnectionFactory got an unresolved address, addr: {}", rawHost);
Counter unresolvedDiscoveryHost = SpectatorUtils.newCounter(
"unresolvedDiscoveryHost",
connPoolConfigOriginName == null ? "unknownOrigin" : connPoolConfigOriginName);
unresolvedDiscoveryHost.increment();
try {
serverAddr = new InetSocketAddress(rawHost, port);
} catch (RuntimeException e2) {
e1.addSuppressed(e2);
throw e1;
}
}
return serverAddr;
}
示例25
@Test
public void deriveInstanceInfoInternal_discovery() {
InstanceInfo instanceInfo = Builder.newBuilder().setAppName("app").build();
Server s = new DiscoveryEnabledServer(instanceInfo, true);
InstanceInfo actual = DefaultClientChannelManager.deriveInstanceInfoInternal(s);
assertSame(instanceInfo, actual);
}
示例26
@Test
public void pickAddressInternal_discovery() {
InstanceInfo instanceInfo =
Builder.newBuilder().setAppName("app").setHostName("192.168.0.1").setPort(443).build();
Server s = new DiscoveryEnabledServer(instanceInfo, true);
SocketAddress addr = DefaultClientChannelManager.pickAddressInternal(s, "originname");
Truth.assertThat(addr).isInstanceOf(InetSocketAddress.class);
InetSocketAddress socketAddress = (InetSocketAddress) addr;
assertEquals(InetAddresses.forString("192.168.0.1"), socketAddress.getAddress());
assertEquals(443, socketAddress.getPort());
}
示例27
@Test
public void pickAddressInternal_discovery_unresolved() {
InstanceInfo instanceInfo =
Builder.newBuilder().setAppName("app").setHostName("localhost").setPort(443).build();
Server s = new DiscoveryEnabledServer(instanceInfo, true);
SocketAddress addr = DefaultClientChannelManager.pickAddressInternal(s, "originname");
Truth.assertThat(addr).isInstanceOf(InetSocketAddress.class);
InetSocketAddress socketAddress = (InetSocketAddress) addr;
assertTrue(socketAddress.toString(), socketAddress.getAddress().isLoopbackAddress());
assertEquals(443, socketAddress.getPort());
}
示例28
@Override
public List<DiscoveryEnabledServer> getInitialListOfServers() {
return obtainServersViaDiscovery();
}
示例29
@Override
public List<DiscoveryEnabledServer> getUpdatedListOfServers() {
return obtainServersViaDiscovery();
}
示例30
private List<DiscoveryEnabledServer> obtainServersViaDiscovery() {
List<DiscoveryEnabledServer> serverList = new ArrayList<DiscoveryEnabledServer>();
DiscoveryClient discoveryClient = DiscoveryManager.getInstance().getDiscoveryClient();
if (discoveryClient == null) {
return new ArrayList<DiscoveryEnabledServer>();
}
// if (vipAddresses != null) {
// for (String vipAddress : vipAddresses.split(",")) {
// // if targetRegion is null, it will be interpreted as the same
// // region of client
// List<InstanceInfo> listOfinstanceInfo =
// discoveryClient.getInstancesByVipAddress(vipAddress, isSecure,
// targetRegion);
// for (InstanceInfo ii : listOfinstanceInfo) {
// if (ii.getStatus().equals(InstanceStatus.UP)) {
//
// if (shouldUseOverridePort) {
// if (logger.isDebugEnabled()) {
// logger.debug("Overriding port on client name: " + clientName + " to "
// + overridePort);
// }
//
// // copy is necessary since the InstanceInfo builder
// // just uses the original reference,
// // and we don't want to corrupt the global eureka
// // copy of the object which may be
// // used by other clients in our system
// InstanceInfo copy = new InstanceInfo(ii);
//
// if (isSecure) {
// ii = new
// InstanceInfo.Builder(copy).setSecurePort(overridePort).build();
// } else {
// ii = new InstanceInfo.Builder(copy).setPort(overridePort).build();
// }
// }
//
// DiscoveryEnabledServer des = new DiscoveryEnabledServer(ii, isSecure,
// shouldUseIpAddr);
// des.setZone(DiscoveryClient.getZone(ii));
// serverList.add(des);
// }
// }
// if (serverList.size() > 0 && prioritizeVipAddressBasedServers) {
// break; // if the current vipAddress has servers, we dont use
// // subsequent vipAddress based servers
// }
// }
// }
Application application = discoveryClient.getApplication(clientName);
if (application == null) {
logger.error(clientName + "服务未找到");
} else {
for (InstanceInfo ii : application.getInstances()) {
if (ii.getStatus() == InstanceStatus.UP) {
if (shouldUseOverridePort) {
if (logger.isDebugEnabled()) {
logger.debug("Overriding port on client name: " + clientName + " to " + overridePort);
}
// copy is necessary since the InstanceInfo builder
// just uses the original reference,
// and we don't want to corrupt the global eureka
// copy of the object which may be
// used by other clients in our system
InstanceInfo copy = new InstanceInfo(ii);
if (isSecure) {
ii = new InstanceInfo.Builder(copy).setSecurePort(overridePort).build();
} else {
ii = new InstanceInfo.Builder(copy).setPort(overridePort).build();
}
}
DiscoveryEnabledServer des = new DiscoveryEnabledServer(ii, isSecure, shouldUseIpAddr);
des.setZone(DiscoveryClient.getZone(ii));
serverList.add(des);
}
}
}
return serverList;
}