在负载均衡器中,提供了 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