在之前的帖子里有介绍三种主要的IPing机制分别是:DummyPing,NIWSDiscoveryPing,PingUrl其中
- 1.DummyPing 就是默认所有的服务都可用
- NIWSDiscoveryPing是采用Eureka的服务发现,选取服务为UP状态的
- PingUrl是主动的去ping,发送Url到服务器,然后获取服务的可用状态,这个策略前面也讲过,一般不适用,因为如果服务过多,会造成很大的压力。
下面给出部分的源码供了解:
image.png
DummyPing 与 NoOpPing
image.png
image.png
NIWSDiscoveryPing
public boolean isAlive(Server server) {
boolean isAlive = true;
if (server != null && server instanceof DiscoveryEnabledServer) {
DiscoveryEnabledServer dServer = (DiscoveryEnabledServer)server;
InstanceInfo instanceInfo = dServer.getInstanceInfo();
if (instanceInfo != null) {
InstanceStatus status = instanceInfo.getStatus();
if (status != null) {
isAlive = status.equals(InstanceStatus.UP);
}
}
}
return isAlive;
}
可以看到将服务转为Eureka的服务实例,然后找到服务状态为UP状态的服务选取使用。
PingUrl
public boolean isAlive(Server server) {
String urlStr = "";
if (this.isSecure) {
urlStr = "https://";
} else {
urlStr = "http://";
}
urlStr = urlStr + server.getId();
urlStr = urlStr + this.getPingAppendString();
boolean isAlive = false;
HttpClient httpClient = new DefaultHttpClient();
HttpUriRequest getRequest = new HttpGet(urlStr);
String content = null;
try {
HttpResponse response = httpClient.execute(getRequest);
content = EntityUtils.toString(response.getEntity());
isAlive = response.getStatusLine().getStatusCode() == 200;
if (this.getExpectedContent() != null) {
LOGGER.debug("content:" + content);
if (content == null) {
isAlive = false;
} else if (content.equals(this.getExpectedContent())) {
isAlive = true;
} else {
isAlive = false;
}
}
} catch (IOException var11) {
var11.printStackTrace();
} finally {
getRequest.abort();
}
return isAlive;
}
PingUrl 则是发送一个请求到服务,然后拿到之后看是否连接成功,如果可以拿到数据,且与期望值一直,则证明该服务存活着。