负载均衡器(LB)是现代架构的入口。本篇我们将实现一个简单的 L4 (TCP) 负载均衡器。
1. 后端管理
struct backend {
const char *ip;
int port;
int is_up;
};
struct backend pool[] = {
{"10.0.0.1", 80, 1},
{"10.0.0.2", 80, 1}
};2. 调度算法 (Round-Robin)
当新连接到来时,选择下一个可用的后端。
struct backend *select_backend() {
static int idx = 0;
for (int i = 0; i < 2; ++i) {
int cur = (idx + i) % 2;
if (pool[cur].is_up) {
idx = cur + 1;
return &pool[cur];
}
}
return NULL;
}3. 健康检查 (Health Check)
我们需要定期(如每 2 秒)检查后端是否存活。
void check_cb(evutil_socket_t fd, short events, void *arg) {
struct backend *b = arg;
// 尝试 connect
// 如果成功 -> b->is_up = 1
// 如果失败 -> b->is_up = 0
}
// 启动定时器
struct event *ev = event_new(base, -1, EV_PERSIST, check_cb, backend);
struct timeval tv = {2, 0};
event_add(ev, &tv);4. 总结
这个 LB 虽然简单,但具备了核心要素。结合之前的“透明代理”逻辑,你已经可以构建一个功能完备的流量分发网关了。
完整代码: 08-load-balancer.c
上一篇: 08-projects/chat-server.md - 实战:即时聊天 回到首页: ../00-intro/reactor-pattern.md
同主题继续阅读
把当前热点继续串成多页阅读,而不是停在单篇消费。
【Libevent 深度剖析与实战指南】实战:即时聊天 (Chat Server)
构建一个支持多人在线、消息广播的聊天室服务器,学习连接管理与广播逻辑。
【Libevent 深度剖析与实战指南】实战:简易 Redis (Redis-lite)
手写一个兼容 Redis 协议的 KV 存储服务器,学习 RESP 协议解析与内存数据结构管理。
【Libevent 深度剖析与实战指南】实战:SOCKS5 代理
实现一个完整的 SOCKS5 代理服务器,深入理解协议状态机与认证流程。
【Libevent 深度剖析与实战指南】实战:透明代理 (Transparent Proxy)
从零实现一个高性能 TCP 透明代理,掌握 bufferevent 的流量转发与背压 (Backpressure) 控制。