负载均衡设计
负载均衡是分布式系统的基础。
📋 负载均衡算法
常见负载均衡算法:
负载均衡算法对比:
| 算法 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
| 轮询 | 简单、公平 | 不考虑服务器性能 | 服务器性能相同 |
| 加权轮询 | 考虑服务器性能 | 需要配置权重 | 服务器性能不同 |
| 最少连接 | 负载均衡效果好 | 需要跟踪连接数 | 长连接场景 |
| 随机 | 实现简单 | 负载可能不均 | 无特殊要求 |
| IP Hash | 会话保持 | 服务器故障影响大 | 需要会话保持 |
| 一致性Hash | 扩展性好、负载均衡 | 实现复杂 | 分布式缓存 |
🎯 负载均衡实现示例
java
/**
* 负载均衡器接口
*/
public interface LoadBalancer {
/**
* 选择一个服务器
*/
Server selectServer(List<Server> servers, Request request);
}
/**
* 轮询负载均衡器
*/
public class RoundRobinLoadBalancer implements LoadBalancer {
private AtomicInteger counter = new AtomicInteger(0);
@Override
public Server selectServer(List<Server> servers, Request request) {
if (servers == null || servers.isEmpty()) {
throw new IllegalArgumentException("Server list is empty");
}
// 过滤健康服务器
List<Server> healthyServers = servers.stream()
.filter(Server::isHealthy)
.collect(Collectors.toList());
if (healthyServers.isEmpty()) {
throw new IllegalStateException("No healthy servers available");
}
// 轮询选择
int index = counter.getAndIncrement() % healthyServers.size();
return healthyServers.get(index);
}
}🎯 健康检查
健康检查机制: