学习笔记 - 负载均衡

181 阅读2分钟

简介

负载均衡(Load balancing)是一种电子计算机技术,用来在多个计算机(计算机集群)、网络连接、CPU、磁盘驱动器或其他资源中分配负载,以达到优化资源使用、最大化吞吐率、最小化响应时间、同时避免过载的目的。使用带有负载平衡的多个服务器组件,取代单一的组件,可以通过冗余提高可靠性。负载平衡服务通常是由专用软件和硬件来完成。主要作用是将大量作业合理地分摊到多个操作单元上进行执行,用于解决互联网架构中的高并发和高可用的问题。

顺序轮询

服务器排着队一人处理一个请求。

优点

实现了负载均衡。

缺点

假如各个服务器的性能参差不齐,顺序轮询会让性能较差的服务器不堪重负,让性能较好的服务器得不到发挥。

权重顺序轮询

服务器排着队按照各自的权重处理请求。假设服务器 A 权重为 1 ,服务器 B 权重为 3 ,服务器 C 权重为 2 ,排队顺序为 ABC ,那么 12 个请求的服务器分配顺序为:A B B B C C A B B B C C 。

优点

能让性能较差的服务器少处理一些请求,让性能较强的服务器多处理一些请求。

缺点

性能好的服务器往往也架不住连续的请求。

权重交叉轮询

各个服务器轮着处理请求,但权重高的服务器轮到的次数比权重低的服务器多,比如说权重低的服务器每三个周期才被轮到一次,权重高的服务器每个周期都会被轮到。权重交叉轮询与权重顺序轮询的目的都是一样的,都是按照权重来分配请求,但在效果上面权重交叉轮询会更加平滑一些。

Dubbo 权重交叉轮询算法模拟

#include  <bits/stdc++.h>

using namespace std;

struct Obj {
    int id;
    int currentWeight;
    int presetWeight;

    Obj() {}

    Obj(int id, int currentWeight, int presetWeight) :
            id(id), currentWeight(currentWeight), presetWeight(presetWeight) {}
};

int main() {

    vector<Obj> objs;

    int objNum = 3, totalPresetWeight = 0;

    objs.reserve(objNum);

    for (int i = 0; i < objNum; ++i) {
        int presetWeight = (i + 1) * 100;
        totalPresetWeight += presetWeight;
        objs.emplace_back(i + 1, 0, presetWeight);
    }

    int requestTimes = 6;

    while (requestTimes--) {
        int choice;
        int choiceWeight = -1;
        cout << "请求到达\n此时服务器状态:";
        for (int i = 0; i < objNum; ++i) {
            objs[i].currentWeight += objs[i].presetWeight;
            if (objs[i].currentWeight > choiceWeight) {
                choiceWeight = objs[i].currentWeight;
                choice = i;
            }
            cout << "{id:" << objs[i].id << ',' << "weight:" << objs[i].currentWeight << "} ";
        }
        objs[choice].currentWeight -= totalPresetWeight;
        cout << "\n请求分配给服务器:" << objs[choice].id << "\n\n";
    }

    return 0;
}

输出:

Dubbo 权重交叉轮询算法模拟输出

以上仅为个人学习总结,欢迎交流指正。