面试题答案
一键面试负载均衡算法选择及原因
在基于Ruby开发的分布式系统中,选择加权轮询算法较为合适。原因是该算法不仅能像轮询算法一样依次分配请求到各个服务节点,还能根据每个节点的处理能力设置权重,处理能力强的节点被分配到更多请求,从而更合理地利用系统资源。
加权轮询算法Ruby代码实现
class WeightedRoundRobin
def initialize(nodes)
@nodes = nodes
@current_index = 0
@total_weight = @nodes.sum { |_, weight| weight }
end
def get_next_node
loop do
node, weight = @nodes[@current_index]
@current_index = (@current_index + 1) % @nodes.size
if weight > 0
@nodes[@current_index] = [node, weight - 1]
@total_weight -= 1
return node
end
if @total_weight == 0
@nodes.each_with_index do |(node, _), index|
@nodes[index] = [node, @nodes[index][1] + 1]
end
@total_weight = @nodes.sum { |_, weight| weight }
end
end
end
end
# 使用示例
nodes = [['node1', 3], ['node2', 2], ['node3', 1]]
balancer = WeightedRoundRobin.new(nodes)
10.times do
puts balancer.get_next_node
end
加权轮询算法优缺点
- 优点:
- 合理分配资源:能根据节点处理能力分配请求,使性能强的节点承担更多负载,提升整体系统性能。
- 实现相对简单:相比一些复杂算法,加权轮询算法实现难度较低,易于理解和维护。
- 公平性较好:每个节点都有机会被分配到请求,且比例与权重相符,不会出现某个节点长时间闲置的情况。
- 缺点:
- 权重设置困难:准确评估节点处理能力并设置合适权重较难,若权重设置不合理,可能导致负载不均衡。
- 无法动态适应节点状态变化:如果节点在运行过程中处理能力发生变化,不能实时调整请求分配,除非手动调整权重。