springcloud笔记二手写简单ribbon负载均衡算法

定义LoadBalancer负载均衡接口

package com.fox.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;

import java.util.List;

public interface LoadBalancer {
    ServiceInstance instances(List instances);
}

定义负载均衡实现类

package com.fox.springcloud.lb.impl;

import com.fox.springcloud.lb.LoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class LoadBalancerImpl implements LoadBalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    private final int getAndIncrement(int count){
        for (;;){
            int current = atomicInteger.get();
            int next = (current + 1) % count;
            if (atomicInteger.compareAndSet(current, next)){
                return next;
            }
        }
    }
    @Override
    public ServiceInstance instances(List instances) {
        int index = getAndIncrement(instances.size());
        return instances.get(index);
    }
}

消费端使用自定义负载均衡方法

	@Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private LoadBalancer loadBalancer;
	
	@GetMapping("/consumer/payment/lb")
    public String getPaymentLB(){
        List instances = discoveryClient.getInstances("PAYMENT-SERVICE");
        if (instances == null || instances.size() == 0){
            return null;
        } else {
            ServiceInstance instance = loadBalancer.instances(instances);
            URI uri = instance.getUri();
            return restTemplate.getForObject(uri + "/payment/lb", String.class);
        }
    }

你可能感兴趣的:(springcloud学习,java,算法,ribbon)