IPing是Ribbon 框架中,负责检查服务实例是否存活(UP)。
-
IPing
public interface IPing { // 检查是否存活的接口 public boolean isAlive(Server server); }
-
DummyPing
一个虚设的IPing实现,永远返回true。
public class DummyPing extends AbstractLoadBalancerPing { public DummyPing() { } // 直接返回true public boolean isAlive(Server server) { return true; } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { } }
- NoOpPing
什么也不做,直接返回true。
public class NoOpPing implements IPing { @Override public boolean isAlive(Server server) { return true; } }
- PingConstant
一个工具类的IPing实现,只要常量参数为true,则表示服务存活,否则都是失效的服务实例。
public class PingConstant implements IPing { boolean constant = true; public void setConstant(String constantStr) { constant = (constantStr != null) && (constantStr.toLowerCase().equals("true")); } public void setConstant(boolean constant) { this.constant = constant; } public boolean getConstant() { return constant; } public boolean isAlive(Server server) { return constant; } }
- PingUrl
通过request访问服务返回的状态码来判定服务是否存活。
public class PingUrl implements IPing { public boolean isAlive(Server server) { String urlStr = ""; if (isSecure){ urlStr = "https://"; }else{ urlStr = "http://"; } urlStr += server.getId(); urlStr += 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 (getExpectedContent()!=null){ LOGGER.debug("content:" + content); if (content == null){ isAlive = false; }else{ if (content.equals(getExpectedContent())){ isAlive = true; }else{ isAlive = false; } } } } catch (IOException e) { e.printStackTrace(); }finally{ // Release the connection. getRequest.abort(); } return isAlive; } }
- NIWSDiscoveryPing
通过Eureka来判定服务实例是否存活。
public class NIWSDiscoveryPing extends AbstractLoadBalancerPing { public boolean isAlive(Server server) { boolean isAlive = true; if (server!=null && server instanceof DiscoveryEnabledServer){ DiscoveryEnabledServer dServer = (DiscoveryEnabledServer)server; // 通过Eureka的服务机制来判定服务是否存活 InstanceInfo instanceInfo = dServer.getInstanceInfo(); if (instanceInfo!=null){ InstanceStatus status = instanceInfo.getStatus(); if (status!=null){ isAlive = status.equals(InstanceStatus.UP); } } } return isAlive; } }
原创文章,作者:3628473679,如若转载,请注明出处:https://blog.ytso.com/195845.html