系统列表
Distributed Systems in Go:生产级分布式平台 SDK 与微服务实战
专栏《分布式 Go 系统工程》配套完整代码实战工程,涵盖并发模型、消息队列适配、Saga 编排、弹性容错与可观测性等生产级模式。
README.mdSYSTEM.mdcmd/auth/main.gocmd/gateway/main.gocmd/orders/main.goconfig/grafana/datasources/datasources.yamlconfig/prometheus.yamlconfig/tempo.yamldeploy/kube/orderflow-infra.yamldocker-compose.ymlgo.modgo.suminternal/auth/handler.gointernal/auth/service.gointernal/domain/events.gointernal/inventory/handler.gointernal/inventory/service.gointernal/notifications/service.gointernal/orders/handler.gointernal/orders/service.gointernal/payment/service.gomigrations/000001_init_schema.up.sqlpkg/platform/auth/auth_test.gopkg/platform/auth/claims.gopkg/platform/auth/jwks.gopkg/platform/auth/middleware.gopkg/platform/auth/password.gopkg/platform/auth/token.gopkg/platform/cli/cli_test.gopkg/platform/cli/health.gopkg/platform/concurrency/context.gopkg/platform/concurrency/shutdown.gopkg/platform/concurrency/shutdown_test.gopkg/platform/concurrency/workerpool.gopkg/platform/concurrency/workerpool_test.gopkg/platform/config/config_test.gopkg/platform/config/loader.gopkg/platform/consistency/consistency_test.gopkg/platform/consistency/idempotency.gopkg/platform/consistency/optimistic.gopkg/platform/consistency/saga.gopkg/platform/ctxutil/context.gopkg/platform/ctxutil/context_test.gopkg/platform/ctxutil/keys.gopkg/platform/database/database_test.gopkg/platform/database/errors.gopkg/platform/database/migrate.gopkg/platform/database/pool.gopkg/platform/database/retry.gopkg/platform/database/tx.gopkg/platform/messaging/fake.gopkg/platform/messaging/fake_test.gopkg/platform/messaging/interfaces.gopkg/platform/messaging/kafka/consumer.gopkg/platform/messaging/kafka/producer.gopkg/platform/messaging/nats/publisher.gopkg/platform/messaging/nats/subscriber.gopkg/platform/messaging/schema.gopkg/platform/middleware/bodyclose.gopkg/platform/middleware/chain.gopkg/platform/middleware/cors.gopkg/platform/middleware/errors.gopkg/platform/middleware/health.gopkg/platform/middleware/logging.gopkg/platform/middleware/middleware_test.gopkg/platform/middleware/recover.gopkg/platform/middleware/requestid.gopkg/platform/middleware/timeout.gopkg/platform/observability/context.gopkg/platform/observability/logger.gopkg/platform/observability/metrics.gopkg/platform/observability/observability_test.gopkg/platform/observability/tracing.gopkg/platform/orchestration/budget.gopkg/platform/orchestration/degrade.gopkg/platform/orchestration/fanout.gopkg/platform/orchestration/orchestration_test.gopkg/platform/resilience/circuit.gopkg/platform/resilience/resilience_test.gopkg/platform/resilience/retry.gotests/live_infra_test.gotests/orderflow_integration_test.go
pkg/platform/observability/metrics.go
| package observability |
| import ( |
| "fmt" |
| "net/http" |
| "strings" |
| "sync" |
| "sync/atomic" |
| "time" |
| "distributed-systems-in-go/pkg/platform/middleware" |
| ) |
| // MetricsRegistry maintains application metrics in memory and exports them in Prometheus format. |
| type MetricsRegistry struct { |
| mu sync.RWMutex |
| counters map[string]*atomic.Uint64 |
| latencySum map[string]*atomic.Uint64 // in milliseconds |
| latencyCount map[string]*atomic.Uint64 |
| } |
| // Global default registry |
| var DefaultRegistry = NewMetricsRegistry() |
| // NewMetricsRegistry initializes a metrics registry. |
| func NewMetricsRegistry() *MetricsRegistry { |
| return &MetricsRegistry{ |
| counters: make(map[string]*atomic.Uint64), |
| latencySum: make(map[string]*atomic.Uint64), |
| latencyCount: make(map[string]*atomic.Uint64), |
| } |
| } |
| // IncCounter increments a counter metric by 1. |
| func (r *MetricsRegistry) IncCounter(name string, labels map[string]string) { |
| key := metricKey(name, labels) |
| r.mu.Lock() |
| c, ok := r.counters[key] |
| if !ok { |
| c = &atomic.Uint64{} |
| r.counters[key] = c |
| } |
| r.mu.Unlock() |
| c.Add(1) |
| } |
| // ObserveLatency records an observation in milliseconds. |
| func (r *MetricsRegistry) ObserveLatency(name string, labels map[string]string, d time.Duration) { |
| key := metricKey(name, labels) |
| ms := uint64(d.Milliseconds()) |
| r.mu.Lock() |
| sum, ok := r.latencySum[key] |
| if !ok { |
| sum = &atomic.Uint64{} |
| r.latencySum[key] = sum |
| } |
| count, ok := r.latencyCount[key] |
| if !ok { |
| count = &atomic.Uint64{} |
| r.latencyCount[key] = count |
| } |
| r.mu.Unlock() |
| sum.Add(ms) |
| count.Add(1) |
| } |
| // PrometheusHandler exposes the metrics at /metrics in standard Prometheus text format. |
| func (r *MetricsRegistry) PrometheusHandler() http.HandlerFunc { |
| return func(w http.ResponseWriter, req *http.Request) { |
| w.Header().Set("Content-Type", "text/plain; version=0.0.4") |
| r.mu.RLock() |
| defer r.mu.RUnlock() |
| var sb strings.Builder |
| for key, counter := range r.counters { |
| sb.WriteString(fmt.Sprintf("%s %d\n", key, counter.Load())) |
| } |
| for key, sum := range r.latencySum { |
| count := r.latencyCount[key].Load() |
| sb.WriteString(fmt.Sprintf("%s_sum_ms %d\n", key, sum.Load())) |
| sb.WriteString(fmt.Sprintf("%s_count %d\n", key, count)) |
| } |
| _, _ = w.Write([]byte(sb.String())) |
| } |
| } |
| // HTTPMetricsMiddleware instruments HTTP requests with request count and latency metrics. |
| func HTTPMetricsMiddleware(registry *MetricsRegistry) middleware.Middleware { |
| if registry == nil { |
| registry = DefaultRegistry |
| } |
| return func(next http.Handler) http.Handler { |
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| start := time.Now() |
| next.ServeHTTP(w, r) |
| duration := time.Since(start) |
| labels := map[string]string{ |
| "method": r.Method, |
| "path": r.URL.Path, |
| } |
| registry.IncCounter("http_requests_total", labels) |
| registry.ObserveLatency("http_request_duration_ms", labels, duration) |
| }) |
| } |
| } |
| func metricKey(name string, labels map[string]string) string { |
| if len(labels) == 0 { |
| return name |
| } |
| var pairs []string |
| for k, v := range labels { |
| pairs = append(pairs, fmt.Sprintf("%s=\"%s\"", k, v)) |
| } |
| return fmt.Sprintf("%s{%s}", name, strings.Join(pairs, ",")) |
| } |