平滑加权轮询算法

平滑加权轮询算法及代码

参考文章:https://www.jianshu.com/p/836193df61db;写的很详细,我只能写点自己的理解。

事件:针对不同权重的不同服务器,进行选择,优先选择权重大的服务器
解决:为每台服务器设置id,权重,有效权重的属性
1.遍历服务器,为每台服务器设置id,权重,有效权重,使得有效权重与权重相同
2.获取当前有效权重最大的服务器,并计算权重和
3.使得当前有效权重最大服务器的有效权重减去总权重
4.使得每一台服务的有效权重设为当前权重加上有效权重
5.返回有效权重最大的服务器Id

理解:首先将获取当前最大的权重的服务器,然后减去总权重,
其次将有效权重,加上各服务器的权重,相当于服务器的当前权重和加上总权重
保证服务器的当前权重和不变。

四台服务器权重分别为1,2,3,4

   1   2   3   4
1   2    4   6   -2
2   3    6  -1   2
3   4   -2   2   6
4   5   0    5   0
5   -4   2   8   4
6   -3   4   1   8
7   -2   6   4   2
8   -1   -2   7   6
9   0   0    0   0
10   1    2   3    4

 代码如下

 服务器

package com.WeightService;

import java.util.List;

public class Service {
public Service(String id, int weight, int weightNow) {
this.id = id;
this.weight = weight;
this.weightNow = weightNow;
}

private String id;
private int weight;
private int weightNow;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public int getWeight() {
return weight;
}

public void setWeight(int weight) {
this.weight = weight;
}

public int getWeightNow() {
return weightNow;
}

public void setWeightNow(int weightNow) {
this.weightNow = weightNow;
}
}

算法
package com.WeightService;


import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class WeightService {

public static void main(String[] args) {
//总的任务
System.out.println("输入轮询次数");
Scanner sc = new Scanner(System.in);
int total = sc.nextInt();
//服务器
int totalWeight = 0;
System.out.println("输入服务器个数");
Scanner test = new Scanner(System.in);
int num = test.nextInt();
List<Service> serviceList = new ArrayList<>();

for (int i = 0; i < num; i++) {
System.out.println("输入服务器" + i + "的权重");
Scanner scanner = new Scanner(System.in);
int weight = scanner.nextInt();
totalWeight = totalWeight + weight;
serviceList.add(i, new Service(i + "", weight, weight));
}

for (int i = 0; i < total; i++) {
String server = getServer(serviceList, totalWeight);
System.out.println(server);
}
}

public static String getServer(List<Service> serviceList, int totalWeight) {
Service maxWeightService = null;
for (int i = 0; i < serviceList.size(); i++) {
if (maxWeightService == null) {
maxWeightService = serviceList.get(i);
}
if (serviceList.get(i).getWeightNow() > maxWeightService.getWeightNow()) {
maxWeightService = serviceList.get(i);
}
System.out.println(i + "-->" + serviceList.get(i).getWeightNow());
}
String Id = maxWeightService.getId();
serviceList.get(Integer.valueOf(Id).intValue()).setWeightNow(maxWeightService.getWeightNow() - totalWeight);
System.out.println(totalWeight);
for (int i = 0; i < serviceList.size(); i++) {

Service service = serviceList.get(i);
if (service != null) {
service.setWeightNow(service.getWeightNow() + service.getWeight());
}
}
return (maxWeightService.getId());
}

}

 

posted @ 2019-08-15 09:49  LinkPlay  阅读(812)  评论(0)    收藏  举报