在負載均衡器中,提供了 Ping 機制,每隔一段時間,會去 Ping 服務器,判斷服務器是否存活,該工作由 com.netflix.loadbalancer.IPing 接口的實現類負責,如果單獨使用 Ribbon 默認情況下不會激活 Ping 機制,默認的實現類為 DummyPing(不驗證),下面實現自定義的Ping 類,代碼如下:
package org.lixue.ribbon.client;
import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.Server;
public class MyPing implements IPing{
public boolean isAlive(Serverserver){
System.out.println("isAlive"+server.getHostPort());
return true;
}
}
修改 src/main/resources 目錄下的 ribbon-client.properties 配置如下:
#配置服務器列表
MyRibbonClient.ribbon.listOfServers=localhost:8080,localhost:8002
#配置負載均衡規則IRule的實現類
MyRibbonClient.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.WeightedResponseTimeRule
#配置負載均衡實現類
MyRibbonClient.ribbon.NFLoadBalancerClassName=com.netflix.loadbalancer.ZoneAwareLoadBalancer
#配置IPing的實現類
MyRibbonClient.ribbon.NFLoadBalancerPingClassName=org.lixue.ribbon.client.MyPing
#配置Ping操作的間隔
MyRibbonClient.ribbon.NFLoadBalancerPingInterval=2
啟動項目可以看到輸出如下:
isAlive localhost:8080
isAlive localhost:8002
request localhost:8002 active true
request localhost:8080 active true
request localhost:8002 active true
request localhost:8080 active true
request localhost:8002 active true
request localhost:8080 active true
request localhost:8002 active true
request localhost:8080 active true
request localhost:8002 active true
request localhost:8080 active true