package nsqbus import ( "context" "encoding/json" "fmt" "net/http" "net/url" "time" ) type nsqdStats struct { Topics []struct { TopicName string `json:"topic_name"` Depth int64 `json:"depth"` Channels []struct { Depth int64 `json:"depth"` DeferredCount int64 `json:"deferred_count"` } `json:"channels"` } `json:"topics"` } // TopicBacklog 读取 nsqd 上某 topic 的积压量:topic 未分发量 + 各 channel 待消费量与延迟重投量(不含处理中)。 // topic 不存在时返回 0。 func TopicBacklog(ctx context.Context, nsqdTCPAddress, topic string) (int64, error) { httpAddress := nsqdHTTPAddress(nsqdTCPAddress) if httpAddress == "" { return 0, fmt.Errorf("nsqd 地址无效:%s", nsqdTCPAddress) } requestCtx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() endpoint := "http://" + httpAddress + "/stats?format=json&topic=" + url.QueryEscape(topic) request, err := http.NewRequestWithContext(requestCtx, http.MethodGet, endpoint, nil) if err != nil { return 0, err } response, err := http.DefaultClient.Do(request) if err != nil { return 0, err } defer response.Body.Close() if response.StatusCode != http.StatusOK { return 0, fmt.Errorf("读取 nsqd 统计失败,HTTP %d", response.StatusCode) } var stats nsqdStats if err := json.NewDecoder(response.Body).Decode(&stats); err != nil { return 0, err } var backlog int64 for _, item := range stats.Topics { if item.TopicName != topic { continue } backlog += item.Depth for _, channel := range item.Channels { backlog += channel.Depth + channel.DeferredCount } } return backlog, nil }