土法炼钢兴趣小组的算法知识备份

【Libevent】实战:负载均衡器 (Load Balancer)

源码下载

本文相关源码已整理,共 1 个文件。

打开下载目录 →

目录

负载均衡器(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 专题索引


By .