IPing是Ribbon 框架中,負(fù)責(zé)檢查服務(wù)實(shí)例是否存活(UP)。
成都創(chuàng)新互聯(lián)成都網(wǎng)站建設(shè)按需設(shè)計(jì),是成都網(wǎng)站制作公司,為成都地磅秤提供網(wǎng)站建設(shè)服務(wù),有成熟的網(wǎng)站定制合作流程,提供網(wǎng)站定制設(shè)計(jì)服務(wù):原型圖制作、網(wǎng)站創(chuàng)意設(shè)計(jì)、前端HTML5制作、后臺(tái)程序開(kāi)發(fā)等。成都網(wǎng)站制作熱線:18982081108IPing
public interface IPing { // 檢查是否存活的接口 public boolean isAlive(Server server); }
DummyPing
一個(gè)虛設(shè)的IPing實(shí)現(xiàn),永遠(yuǎn)返回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; } }
一個(gè)工具類(lèi)的IPing實(shí)現(xiàn),只要常量參數(shù)為true,則表示服務(wù)存活,否則都是失效的服務(wù)實(shí)例。
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; } }
通過(guò)request訪問(wèn)服務(wù)返回的狀態(tài)碼來(lái)判定服務(wù)是否存活。
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); // 根據(jù)狀態(tài)碼和返回的內(nèi)容來(lái)判定服務(wù)實(shí)例是否有效 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; } }
通過(guò)Eureka來(lái)判定服務(wù)實(shí)例是否存活。
public class NIWSDiscoveryPing extends AbstractLoadBalancerPing { public boolean isAlive(Server server) { boolean isAlive = true; if (server!=null && server instanceof DiscoveryEnabledServer){ DiscoveryEnabledServer dServer = (DiscoveryEnabledServer)server; // 通過(guò)Eureka的服務(wù)機(jī)制來(lái)判定服務(wù)是否存活 InstanceInfo instanceInfo = dServer.getInstanceInfo(); if (instanceInfo!=null){ InstanceStatus status = instanceInfo.getStatus(); if (status!=null){ isAlive = status.equals(InstanceStatus.UP); } } } return isAlive; } }