测试 Goreplay - 使用真实流量测试你的应用

xiaocui · 2018年11月13日 · 最后由 IDbbnn345 回复于 2018年11月18日 · 13339 次阅读
本帖已被管理员设置为精华贴

场景描述:

最近项目准备升级,其中一个步骤就是需要删除一些不再维护的 gem,这样就会涉及大量代码的修改,除了增加测试覆盖率以外,最好能使用线上真实的流量来访问测试环境,然后通过 newrelic 更加详尽的捕捉潜在的错误。

那这里就涉及到流量分流或者流量复制的问题,而 goreplay 便是解决该问题的一个优秀的工具。 顾名思义,goreplay 是基于 go 语言实现的,要在生产服务器上安装 go 环境。

安装参考:https://golang.org/doc/install

准备好 go 语言环境后,goreplay 直接提供了编译好的版本,十分方便,直接解压即可,可参考以下步骤:

# 请自行安装最新版本
wget https://github.com/buger/goreplay/releases/download/v0.16.1/gor_0.16.1_x64.tar.gz
tar xvf gor_0.16.1_x64.tar.gz

下面是 goreplay 官方的图例,简单来讲就是 goreplay 捕捉线上流量,并将捕捉到的流量释放到测试服务器上。

image

Goreplay 基本用法

注:本文中使用 sudo 权限执行,如需要权限配置,参考: https://github.com/buger/goreplay/wiki/Running-as-non-root-user

  1. 捕捉流量并通过终端输出 (调试)
sudo ./goreplay --input-raw :8000 --output-stdout

上述命令将监控 8000 端口上所有的流量,并通过终端 stdout 输出。你可以通过浏览器或者 curl 访问 8000 端口,然后在终端查看 gor 输出所有的 http 请求。

2.捕捉流量并实时同步到另一台机器

sudo ./goreplay --input-raw :8000 --output-http="http://example:8001"

上述命令将 8000 端口的流量实时同步访问http://example:8001服务器,你在访问第一台服务器时,将看到流量以相同的顺序请求到第二台。

3.将捕捉流量保存到文件中,然后释放到其它机器 有时候实时同步流量是很难做到的,所以 Goreplay 提供了这种先保存后释放的模式: 第一步,通过--output-file 保存流量:

sudo ./goreplay --input-raw :8000 --output-file=requests.gor

上述命令将 8000 端口的流量,保存到 requests.gor 文件中 (必须是.gor 后缀,其它后缀经测释放时有问题)。

第二步,释放保存的流量:

sudo ./goreplay --input-file requests.gor --output-http="http://localhost:8001"

上述命令将释放所有保存在 requests.gor 中的请求通过相同的时间顺序释放到服务器http://localhost:8001

参数解释:

--input-raw   #用来捕捉http流量,需要指定ip地址和端口
--input-file   #接收通过--output-file保存流量的文件
--input-tcp #将多个 Goreplay 实例获取的流量聚集到一个 Goreplay 实例
--output-stdout  #终端输出
--output-tcp #将获取的流量转移至另外的 Goreplay 实例
--output-http  #流量释放的对象server,需要指定ip地址和端口
--output-file   #录制流量时指定的存储文件
Goreplay 的限速机制和请求过滤
  1. 限速机制: 由于生产服务器配置一般远高于测试服务器配置,所以直接将生产服务器全部流量同步到测试服务器是不可行的,goreplay 提供了两种策略:

a. 限制每秒的请求数

sudo ./goreplay  --input-tcp :28020 --output-http "http://staging.com|10"# (每秒请求数限制10个以内)
sudo ./goreplay  --input-raw :80 --output-tcp "replay.local:28020|10%"  # (每秒请求数限制10%以内)

b. 基于 Header 或 Url 的参数限制一些请求,为指定的 header 或者 url 的请求设定限制的百分比。

sudo ./goreplay  --input-raw :80 --output-tcp "replay.local:28020|10%" --http-header-limiter "X-API-KEY: 10%"
sudo ./goreplay  --input-raw :80 --output-tcp "replay.local:28020|10%" --http-param-limiter "api_key: 10%"
  1. 请求过滤: 当你需要捕捉指定路径的请求流量时,可以使用该机制,如只同步/api 路径下的请求 bash sudo ./goreplay --input-raw :8080 --output-http staging.com --http-allow-url /api

另外还有其它一些参数用法:

--http-disallow-url    #不允许正则匹配的Url
--http-allow-header #允许的 Header 头
--http-disallow-header #不允许的 Header 头
--http-allow-method #允许的请求方法,传入值为GET, POST, OPTIONS等

更多参考官方文档:https://github.com/buger/goreplay/wiki/Getting-Started

huacnlee 将本帖设为了精华贴。 11月14日 10:33
需要 登录 后方可回复, 如果你还没有账号请 注册新账号