java有序轮训_java 实现Nginx加权重轮训

java 实现Nginx加权重轮训

代码灵感来源网站,看不懂代码先阅读网站:Nginx 加权轮训

public class WeightedRoundRobinSchedulingDemo {

static class Service {

private String ip;//ip地址

private Integer weight;//权重值

private Integer currentWeight;//当前权重轮训

private Integer effectiveWeight;//偏移权重

private Integer total;//总的权重数

public Service(String ip, Integer weight) {

this.weight = weight;

this.ip = ip;

this.effectiveWeight =this.weight;

this.currentWeight =0;

}

public Service() {

}

public String getIp() {

return ip;

}

public void setIp(String ip) {

this.ip = ip;

}

public Integer getWeight() {

return weight;

}

public void setWeight(Integer weight) {

this.weight = weight;

}

public Integer getCurrentWeight() {

return currentWeight;

}

public void setCurrentWeight(Integer currentWeight) {

this.currentWeight = currentWeight;

}

public Integer getEffectiveWeight() {

return effectiveWeight;

}

public void setEffectiveWeight(Integer effectiveWeight) {

this.effectiveWeight = effectiveWeight;

}

}

public static Listservices =new ArrayList<>();

static {

services.add(new Service("192.168.1.1",6));

services.add(new Service("192.168.1.2",3));

services.add(new Service("192.168.1.3",1));

}

public static Service getService() {

HashSet set =new HashSet<>();

int sum =services.stream().mapToInt(Service::getEffectiveWeight).sum();//算出应该轮训多少次6+ 3 + 1

OptionalInt max =services.stream().mapToInt(Service::getEffectiveWeight).max();//选出每回权重最大的就是当前该选中的

for (int i =0; i

Service service =services.get(i);

if (service.getEffectiveWeight().equals(max.getAsInt()) && !set.contains(service.getEffectiveWeight())) {

service.setCurrentWeight(service.getEffectiveWeight()-sum);

set.add(service.getEffectiveWeight());

}else {

service.setCurrentWeight(service.getEffectiveWeight());

}

service.setEffectiveWeight(service.getWeight()+service.getCurrentWeight());

services.set(i, service);

}

Optional min =services.stream().min(Comparator.comparing(Service::getCurrentWeight));

return min.get();

}

public static void main(String[] args) {

for (int i =0; i <10; i++) {

Service service =getService();

System.out.println(JSON.toJSONString(service));

}

}

}

标签:java,轮训,Service,ip,weight,Nginx,service,Integer,public

来源: https://blog.csdn.net/qq_26802811/article/details/110776477

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值