系统相关
首页 > 系统相关> > java 实现Nginx加权重轮训

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