服务发现与负载均衡通过注册中心和算法实现动态寻址与流量分发。服务启动时向注册中心(如Etcd)注册并定期发送心跳,消费者查询健康实例列表;负载均衡采用轮询、随机、最少连接或加权轮询等策略选择节点,确保请求合理分发。示例中使用Etcd存储服务信息,结合心跳TTL判断存活,客户端获取实例后通过RoundRobin等算法选取目标进行调用。关键在于保持注册实时性与策略适配业务需求。

服务发现与负载均衡是现代分布式系统中的核心组件,尤其在微服务架构中尤为重要。它们确保服务之间可以动态找到彼此,并将请求合理地分发到可用的服务实例上。下面通过一个简单示例说明其基本实现思路。
服务发现的核心是让服务提供者注册自己,服务消费者能够查询到可用的实例列表。
以基于心跳机制的注册中心为例:
示例伪代码:
class ServiceRegistry:
def register(service_name, ip, port):
key = f"services/{service_name}/{ip}:{port}"
etcd.put(key, "alive", ttl=10) // 设置TTL自动过期
<pre class='brush:php;toolbar:false;'>def heartbeat(service_name, ip, port):
key = f"services/{service_name}/{ip}:{port}"
etcd.refresh_ttl(key, ttl=10)
def get_instances(service_name):
return etcd.get_prefix(f"services/{service_name}") // 返回所有健康实例获取到服务实例列表后,客户端或网关需选择一个节点进行调用。以下是几种常用算法的实现方式。
1. 轮询(Round Robin)
按顺序轮流选择实例,适合实例性能相近的场景。
class RoundRobinBalancer:
def __init__(self, instances):
self.instances = instances
self.index = 0
<pre class='brush:php;toolbar:false;'>def next(self):
if not self.instances: return None
instance = self.instances[self.index]
self.index = (self.index + 1) % len(self.instances)
return instance2. 随机(Random)
随机选择一个实例,实现简单且分布较均匀。
import random
class RandomBalancer:
def __init__(self, instances):
self.instances = instances
<pre class='brush:php;toolbar:false;'>def select(self):
if not self.instances: return None
return random.choice(self.instances)3. 最少连接数(Least Connections)
选择当前连接数最少的实例,适用于长连接或处理时间差异大的场景。
class LeastConnectionsBalancer:
def __init__(self, instances):
self.connections = {instance: 0 for instance in instances}
<pre class='brush:php;toolbar:false;'>def select(self):
return min(self.connections, key=self.connections.get)
def incr(instance):
self.connections[instance] += 1
def decr(instance):
self.connections[instance] -= 14. 加权轮询(Weighted Round Robin)
根据实例权重分配请求,高配机器承担更多流量。
class WeightedRoundRobin:
def __init__(self, instance_weights):
# instance_weights = [("192.168.1.1:8080", 3), ("192.168.1.2:8080", 1)]
self.instance_weights = instance_weights
self.current_index = 0
self.gcd = self._gcd(weights) # 可选:优化循环周期
<pre class='brush:php;toolbar:false;'>def select(self):
if not self.instance_weights: return None
max_weight = max(w for _, w in self.instance_weights)
while True:
for instance, weight in self.instance_weights:
if weight >= max_weight:
return instance在实际调用中,通常先从注册中心获取实例,再通过负载均衡器选择目标。
# 模拟一次服务调用
registry = ServiceRegistry()
instances = registry.get_instances("user-service")
<p>if not instances:
raise Exception("No available instances")</p><p>balancer = RoundRobinBalancer(instances)
target = balancer.next()</p><p>http.get(f"<a href="https://www.php.cn/link/c2090502cd75f701449abad130cce798">https://www.php.cn/link/c2090502cd75f701449abad130cce798</a>")</p>基本上就这些。实际系统中可结合健康检查、熔断降级、DNS或多级缓存优化性能。关键是保持注册信息实时准确,负载策略贴合业务特征。不复杂但容易忽略细节,比如心跳间隔设置不合理会导致误判。
以上就是服务发现与负载均衡算法实现示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号