orangesoft/throttler

节点之间的负载均衡器。

3.0.0 2024-06-28 12:50 UTC

This package is auto-updated.

Last update: 2024-08-28 13:14:31 UTC


README

Build Status Latest Stable Version Packagist PHP Version Support Total Downloads License

节点之间的负载均衡器。

安装

您可以通过 Composer 安装最新版本

composer require orangesoft/throttler

此包需要 PHP 8.1 或更高版本。

快速使用

按照以下方式配置 Orangesoft\Throttler\WeightedRoundRobinThrottler::class 并为每个节点设置权重,如果您使用的是加权策略

<?php

use Orangesoft\Throttler\Counter\InMemoryCounter;
use Orangesoft\Throttler\Collection\NodeInterface;
use Orangesoft\Throttler\Collection\Node;
use Orangesoft\Throttler\WeightedRoundRobinThrottler;

$throttler = new WeightedRoundRobinThrottler(
    new InMemoryCounter(),
);

$collection = new InMemoryCollection([
    new Node('192.168.0.1', 5),
    new Node('192.168.0.2', 1),
    new Node('192.168.0.3', 1),
]);

while (true) {
    /** @var NodeInterface $node */
    $node = $throttler->pick($collection);

    // ...
}

因此,限流器将遍历所有节点,并根据选择的策略返回适当的节点,如下所示

+---------+-------------+
| request | node        |
+---------+-------------+
|       1 | 192.168.0.1 |
|       2 | 192.168.0.1 |
|       3 | 192.168.0.1 |
|       4 | 192.168.0.1 |
|       5 | 192.168.0.1 |
|       6 | 192.168.0.2 |
|       7 | 192.168.0.3 |
|       n | etc.        |
+---------+-------------+

以下限流器可用

基准测试

运行 composer phpbench 查看基准测试

+-------------------------------+------+-----+----------+----------+----------+---------+
| benchmark                     | revs | its | mean     | best     | worst    | stdev   |
+-------------------------------+------+-----+----------+----------+----------+---------+
| RandomBench                   | 1000 | 5   | 4.002μs  | 3.880μs  | 4.097μs  | 0.073μs |
| WeightedRandomBench           | 1000 | 5   | 11.660μs | 11.533μs | 11.797μs | 0.094μs |
| FrequencyRandomBench          | 1000 | 5   | 6.074μs  | 5.924μs  | 6.242μs  | 0.139μs |
| RoundRobinBench               | 1000 | 5   | 4.060μs  | 3.888μs  | 4.363μs  | 0.171μs |
| WeightedRoundRobinBench       | 1000 | 5   | 10.778μs | 10.655μs | 10.919μs | 0.115μs |
| SmoothWeightedRoundRobinBench | 1000 | 5   | 6.888μs  | 6.707μs  | 7.102μs  | 0.130μs |
+-------------------------------+------+-----+----------+----------+----------+---------+

报告基于速度测量。查看 best 列以找出哪个策略最快。

文档

Sam Rose 的博客 上了解更多关于负载均衡的信息。