那里有卖百度云资源➕扣
作者:互联网
根据 LoadBalancer 实现负载能力
Ribbon 的负载能力,根据动态列表选择服务器,Spring Could 中大多使用这个功能。
//负载规则算法
IRule rule = new AvailabilityFilteringRule();
//服务列表
ServerList list = new DiscoveryEnabledNIWSServerList("MyVIP:7001");
//过滤器
ServerListFilter filter = new ZoneAffinityServerListFilter();
//LoadBalancer
ZoneAwareLoadBalancer lb = LoadBalancerBuilder.newBuilder()
.withDynamicServerList(list)
.withRule(rule)
.withServerListFilter(filter)
.buildDynamicServerListLoadBalancer();
//选择服务器
DiscoveryEnabledServer server = lb.chooseServer();
通过 LoadBalancerCommand 命令完成请求和负载
Ribbon 还提供使用命令模式的请求方法 ,主要通过 LoadBalancerCommand 实现。
/**
* 通过命令模式发送请求
*/
public class URLConnectionLoadBalancer {
private final ILoadBalancer loadBalancer;
public URLConnectionLoadBalancer(List serverList) {
loadBalancer = LoadBalancerBuilder.newBuilder().buildFixedServerListLoadBalancer(serverList);
}
//通过 LoadBalancerCommand 发送请求
public String call(final String path) {
return LoadBalancerCommand.builder()
.withLoadBalancer(loadBalancer)
.build()
.submit(server -> {
URL url;
try {
url = new URL("http://" + server.getHost() + ":" + server.getPort() + path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
return Observable.just(conn.getResponseMessage());
} catch (Exception e) {
return Observable.error(e);
}
}).toBlocking().first();
}
//获取 ILoadBalancer 状态
public LoadBalancerStats getLoadBalancerStats() {
return ((BaseLoadBalancer) loadBalancer).getLoadBalancerStats();
}
public static void main(String[] args) {
//添加服务列表
URLConnectionLoadBalancer urlLoadBalancer = new URLConnectionLoadBalancer(Lists.newArrayList(
new Server("ip.taobao.com", 80),
new Server("www.linkedin.com", 80),
new Server("www.yahoo.com", 80)));
//循环请求
for (int i = 0; i < 6; i++) {
System.out.println(urlLoadBalancer.call("/"));
}
System.out.println("=== Load balancer stats ===");
System.out.println(urlLoadBalancer.getLoadBalancerStats());
}
}
通过 IClient 完成请求和负载
Ribbon 还可以通过 com.netflix.client.IClient 完成请求和负载。
public class MyIClient {
public static void main(String[] args) throws Exception {
//设置负载地址列表
List servers = Lists.newArrayList(new Server("www.linkedin.com:80"), new Server("www.examples.com:80"));
//获取 lb
BaseLoadBalancer lb = LoadBalancerBuilder.newBuilder().buildFixedServerListLoadBalancer(servers);
// 获取 client RestClient 是 IClient 的实现类。
RestClient client = (RestClient) ClientFactory.getNamedClient("sample-client");
//给 client 设置 lb
client.setLoadBalancer(lb);
//构建 HttpRequest
HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build();
for (int i = 0; i < 10; i++) {
HttpResponse response = null;
try {
//发送请求
response = client.executeWithLoadBalancer(request);
System.out.println("Status code f
隐藏内容
标签:负载,lb,那里,client,百度,new,com,public,资源 来源: https://www.cnblogs.com/ibdjb/p/13424338.html