package main import ( "sync/atomic" "time" "github.com/myzhan/boomer" ) // OrderPayload 与 python/locustfile.py 的请求体**完全一致**(公平对比前提)。 type OrderPayload struct { UserID int `json:"user_id"` ContractID int `json:"contract_id"` Side string `json:"side"` MarginType int `json:"margin_type"` Quantity string `json:"quantity"` Price string `json:"price,omitempty"` } const userPoolSize = 1000 var ( rngMu atomic.Int64 // 简单计数即可,payload 随机性不影响正确性 openOrder atomic.Int64 // 记录一个最近开仓的 order_id 供撤单用 ) func randIntn(n int) int { // 压测下用原子计数打散即可,不追求密码学随机 return int(rngMu.Add(1) * 2654435761 % (int64(n) * 9973) % int64(n)) } func payload(withPrice bool) OrderPayload { p := OrderPayload{ UserID: randIntn(userPoolSize) + 1, // 真随机用户池:避免全员压同一用户导致分布失真 ContractID: randIntn(3) + 1, MarginType: randIntn(2) + 1, Quantity: "10", } if randIntn(2) == 0 { p.Side = "ask" } else { p.Side = "bid" } if withPrice { p.Price = "30000.5" } return p } // TaskDef 配置驱动的任务注册。若把任务硬写死在 boomer.Run(t1, t2) 里, // 新增任务极易漏注册,且不会有任何报错提示。增删任务只改这张表。 type TaskDef struct { Name string Weight int Fn func(c *APIClient) (method, name string, httpStatus, bizCode int, err error) } func taskTable() []TaskDef { return []TaskDef{ {"limit_open", 4, func(c *APIClient) (string, string, int, int, error) { s, b, err := c.OpenOrder("/api/v1/order/limit/open", payload(true)) return "POST", "/api/v1/order/limit/open", s, b, err }}, {"market_quantity_open", 2, func(c *APIClient) (string, string, int, int, error) { s, b, err := c.OpenOrder("/api/v1/order/market/quantity/open", payload(false)) return "POST", "/api/v1/order/market/quantity/open", s, b, err }}, {"market_amount_open", 2, func(c *APIClient) (string, string, int, int, error) { s, b, err := c.OpenOrder("/api/v1/order/market/amount/open", payload(false)) return "POST", "/api/v1/order/market/amount/open", s, b, err }}, {"batch_cancel", 1, func(c *APIClient) (string, string, int, int, error) { s, b, err := c.BatchCancel(randIntn(userPoolSize)+1, []int64{openOrder.Load()}) return "DELETE", "/api/v1/order/batch/cancel", s, b, err }}, } } // buildBoomerTasks 把任务表转成 boomer.Task 列表。 func buildBoomerTasks(c *APIClient) []*boomer.Task { var tasks []*boomer.Task for _, d := range taskTable() { def := d tasks = append(tasks, &boomer.Task{ Name: def.Name, Weight: def.Weight, Fn: func() { start := time.Now() method, name, httpStatus, bizCode, err := def.Fn(c) elapsed := time.Since(start).Milliseconds() switch { case err != nil: boomer.RecordFailure(method, name, elapsed, err.Error()) case httpStatus != 200 || bizCode != 0: boomer.RecordFailure(method, name, elapsed, "biz error") default: boomer.RecordSuccess(method, name, elapsed, 0) } }, }) } return tasks }