以下是转换后的PHP代码:
以下是转换后的PHP代码:
class WeightedRoundRobin {
private $servers;
private $currentIndex;
private $currentWeight;
private $maxWeight;
public function __construct($postid = 0, $servers = []) {
$this->servers = $servers;
$this->maxWeight = max(array_column($servers, 'weight'));
$this->currentIndex = $postid % count($servers);
$this->currentWeight = $this->maxWeight;
}
public function init() {
$this->currentWeight = $this->maxWeight;
}
public function next() {
while (true) {
$this->currentIndex = ($this->currentIndex + 1) % count($this->servers);
if ($this->currentIndex == 0) {
$this->currentWeight--;
if ($this->currentWeight <= 0) {
$this->currentWeight = $this->maxWeight;
}
}
$selectedServer = $this->servers[$this->currentIndex];
if ($selectedServer['weight'] >= $this->currentWeight) {
return $selectedServer['domain'];
}
}
}
}
// 示例用法
$servers = [
['domain' => 'https://img1.example.com', 'weight' => 3],
['domain' => 'https://img2.example.com', 'weight' => 2],
['domain' => 'https://img3.example.com', 'weight' => 1]
];
$postid = 0;
$generator = new WeightedRoundRobin($postid, $servers);
// 调用示例
echo $generator->next(); // 输出第一个合适的域名
代码解释:
类结构:
WeightedRoundRobin
类封装了加权轮询逻辑,维护状态变量currentIndex
、currentWeight
和maxWeight
。
构造函数:
- 接收
postid
和服务器列表$servers
。 - 计算最大权重
maxWeight
。 - 根据
postid
初始化currentIndex
。 - 设置初始权重
currentWeight
为最大权重。
- 接收
init() 方法:
- 重置当前权重为最大权重,用于重新开始轮询。
next() 方法:
- 使用无限循环查找符合条件的服务器。
- 更新当前索引,当回到起始点时降低权重。
- 检查当前服务器权重是否满足条件,满足则返回域名。
注意事项:
- 确保传入的服务器数组格式正确,包含
domain
和weight
键。 - 使用前需实例化类并传入参数,如示例所示。
- 每次调用
next()
会返回下一个服务器的域名。