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) { } }
什么也不做,直接返回true。
public class NoOpPing implements IPing { @Override public boolean isAlive(Server server) { return true; } }
一个工具类的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; } }
通过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; } }
通过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; } }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。