美文网首页HAProxy
HAProxy源码探索(2):第一个版本

HAProxy源码探索(2):第一个版本

作者: chenj23986526 | 来源:发表于2018-12-23 12:42 被阅读0次

分析方式

为什么要从第一个版本开始分析,这样可以看到整个 HAProxy 版本的发展过程是如何演变的,并从中慢慢消化

让我们开始

  • 切换到第一个版本
    cd haproxy
    git checkout v1.0.0

  • 我们发现目录结构很简单

      - doc
        haproxy.txt
      - examples
        cfg
      - tests
        test.c
      haproxy.c
      Makefile
    
  • 看下 Makefile

    CC = gcc
    LD = gcc
    
    COPTS = -O2 -g -DSTATTIME=0
    LIBS =
    
    # to compile under solaris, uncomment these two lines
    #COPTS = -O2 -fomit-frame-pointer -DSOLARIS
    #LIBS = -lnsl -lsocket
    
    CFLAGS = -Wall $(COPTS)
    LDFLAGS = -g
    
    all: haproxy
    
    haproxy: haproxy.o
      $(LD) $(LDFLAGS) -o $@ $^ $(LIBS)
    
    %.o:  %.c
      $(CC) $(CFLAGS) -c -o $@ $<
    
    clean:
      rm -vf *.[oas] *~ core haproxy test nohup.out gmon.out
    
    
  • 分析 Makefile
    gcc 编译参数:
    -O2 是告诉 gcc 要进行优化 O是优化(Optimize) 2是优化等级
    -g 是使生成的执行文件可以被 gdb 调试
    -DSTATTIME=0 表示预定义宏STATTIME为0(不定义), -D 是预定义宏的选项
    -Wall 表示开启所有警告(Warning)
    后续分析所有关于 gcc 的常用参数不再赘述,忘记时请查阅 man gcc
    变量:
    通常变量CC 表示编译 LD 表示链接

  • 编译第一个版本
    make
    我们得到了 haproxy.o 以及 haproxy可执行文件

  • 先建立一个 http 服务,使用8080端口
    这里为了简单,直接用 Go 写了个 http 服务,只返回ok,编译并启动

    package main
    
    import (
      "fmt"
      "log"
      "net/http"
    )
    
    func handle(w http.ResponseWriter, r *http.Request) {
      fmt.Fprintf(w, "ok")
    }
    
    func main() {
      http.HandleFunc("/", handle)
      log.Fatal(http.ListenAndServe(":8080", nil))
    }
    
    
    
  • 创建配置 haproxy.cfg
    我们使用如下配置

    listen http_proxy 0.0.0.0:3128
      mode    http
      dispatch 127.0.0.1:8080
      contimeout  3000
      clitimeout  150000
      srvtimeout  150000
      maxconn 60000
      redisp
      retries 3
      grace 3000
    
    listen health 0.0.0.0:3130
      mode    health
      clitimeout  1500
      srvtimeout  1500
      maxconn 4
      grace 0
    
  • 启动 HAProxy
    ./haproxy -f haproxy.cfg

  • 测试
    访问 curl http://localhost:3128,得到结果ok

相关文章

网友评论

    本文标题:HAProxy源码探索(2):第一个版本

    本文链接:https://www.haomeiwen.com/subject/vfspkqtx.html