手写轮询算法

Posted 温文艾尔

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了手写轮询算法相关的知识,希望对你有一定的参考价值。

本次的手写轮询算法是跟着周阳老师完成的,这里做一下记录


一、LoadBalancer接口

package com.atguigu.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;

import java.util.List;

/**
 * Description
 * User:
 * Date:
 * Time:
 */
public interface LoadBalancer {
    ServiceInstance instances(List<ServiceInstance> serviceInstances);
}

二、LoadBalancer接口实现类

package com.atguigu.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

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

/**
 * Description
 * User:
 * Date:
 * Time:
 */
@Component
public class MyLB implements LoadBalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAndIncrement(){
        int current;
        int next;
        do {
            current = this.atomicInteger.get();//获取当前atomicInteger值
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        }while (!this.atomicInteger.compareAndSet(current,next));//期望值为current,修改值为next
        System.out.println("*****第几次访问,次数next: "+next);
        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int index = getAndIncrement() % serviceInstances.size();
        ServiceInstance instance = serviceInstances.get(index);

        return instance;
    }
}

三、生产者微服务

    @GetMapping(value = "/payment/lb")
    public String getPaymentLB(){
        return serverPort;
    }

消费者代码

    @GetMapping("/consumer/payment/lb")
    public String getPaymentLB(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PROVIDER-SERVICE");
        if (null==instances ||instances.size()<=0){
            return null;
        }
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();
        System.out.println("uri:"+uri);
        return restTemplate.getForObject(uri+"/payment/lb",String.class);
    }

结果展示


以上是关于手写轮询算法的主要内容,如果未能解决你的问题,请参考以下文章

手写RPC框架,理解更透彻,代码已上传Github!

手写一个RPC框架,理解更透彻(附源码)

手写数字识别——基于全连接层和MNIST数据集

前端面试题之手写promise

手写代码bug百出?不如花两个小时考C认证试试

徒手撸了一个RPC框架,理解更透彻了,代码已上传github,自取~