Skip to content
Go
配置管理

配置管理

go-zero 使用 YAML 作为配置格式,通过 conf.MustLoad 加载并映射为强类型 Go 结构体,支持环境变量覆盖和热更新。


配置文件结构

每个 go-zero 服务都有一个 etc/*.yaml 配置文件:

# API 服务配置示例
Name: user-api
Host: 0.0.0.0
Port: 8888

# 日志
Log:
  ServiceName: user-api
  Mode: console                # console | file | volume
  Level: info                  # debug | info | error | severe
  Path: logs/user-api          # Mode=file 时有效
  KeepDays: 7
  StackCooldownMillis: 100

# Prometheus 监控(默认启用)
Prometheus:
  Host: 0.0.0.0
  Port: 9090
  Path: /metrics

# 链路追踪
Telemetry:
  Name: user-api
  Endpoint: jaeger:4317        # OTLP gRPC 端口
  Sampler: 1.0                 # 采样率 0.0-1.0
  Batcher: otlpgrpc            # otlpgrpc | otlphttp

# 弹性治理
Timeout: 3000                  # 请求超时(毫秒)
MaxConns: 10000               # 最大并发连接数

# 熔断
Breaker: true                  # 默认 true

# JWT 认证
Auth:
  AccessSecret: your-secret-key
  AccessExpire: 86400          # 秒

# RPC 客户端配置
UserRpcConf:
  Etcd:
    Hosts:
      - 127.0.0.1:2379
    Key: user.rpc
  Timeout: 2000

# 数据库
DataSource: root:password@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=true

# Redis 缓存
Cache:
  - Host: 127.0.0.1:6379
    Pass: ""
    Type: node

# 消息队列(Kafka)
KafkaConf:
  Brokers:
    - 127.0.0.1:9092
  Topic: order-events
  Group: order-consumer

# 请求签名
Signature:
  Strict: true
  Expiry: 1h
  PrivateKeys:
    - Fingerprint: "service-a"
      KeyFile: ./secret/id_rsa

# 过载降载
Shedding:
  CpuThreshold: 900            # 0-1000,默认 900

配置加载

基础用法

package main

import (
    "flag"
    "github.com/zeromicro/go-zero/core/conf"
)

var configFile = flag.String("f", "etc/user-api.yaml", "config file path")

func main() {
    flag.Parse()
    var c config.Config
    conf.MustLoad(*configFile, &c)
    // c 就是已经填充好的配置对象
}

配置结构体

package config

import "github.com/zeromicro/go-zero/rest"

type Config struct {
    rest.RestConf                  // 嵌入框架标准配置
    Auth struct {
        AccessSecret string
        AccessExpire int64
    }
    UserRpcConf  zrpc.RpcClientConf
    DataSource   string
    Cache        cache.CacheConf
}

🚨 字段名必须对应 YAML 的 keyconf.MustLoad 使用 YAML key 做映射,YAML 中写 DataSource,Go 结构体中也必须是 DataSource,不能写 datasource


多环境配置

方案1:多配置文件

etc/
├── user-api.yaml        # 基础配置(可被覆盖)
├── user-api-dev.yaml    # 开发环境
├── user-api-staging.yaml # 预发布环境
└── user-api-prod.yaml   # 生产环境
# 启动时指定
go run user.go -f etc/user-api-dev.yaml

方案2:环境变量覆盖

// 从环境变量读取敏感信息
type Config struct {
    rest.RestConf
    DataSource string `json:",env=DB_DSN"`
    Auth struct {
        AccessSecret string `json:",env=JWT_SECRET"`
    }
}

conf.MustLoad 会先读 YAML,再用同名环境变量覆盖:

export DB_DSN="root:secret@tcp(prod-db:3306)/dbname"
export JWT_SECRET="production-secret"
go run user.go

💡 最佳实践:YAML 存非敏感配置,环境变量存密钥、密码等敏感信息


配置热更新

go-zero 通过 etcd 支持配置热更新:

import "github.com/zeromicro/go-zero/core/conf"

var c config.Config
conf.MustLoad(*configFile, &c, conf.UseEtcd("127.0.0.1:2379", "/config/user-api"))

需要配合配置中心使用。更常见的方式是通过 K8s ConfigMap 挂载 + 监听文件变化 实现热更新,go-zero 框架层提供 core/configurator 支持。


API 服务完整配置项

rest.RestConf 中包含的所有标准配置:

配置项 类型 默认值 说明
Name string 服务名称
Host string 0.0.0.0 监听地址
Port int 8888 监听端口
CertFile string HTTPS 证书文件
KeyFile string HTTPS 私钥文件
Timeout int 3000 请求超时(毫秒)
MaxConns int 10000 最大并发连接数
MaxBytes int 请求体最大字节数
Log LogConf 日志配置
Prometheus PrometheusConf 监控配置
Telemetry TelemetryConf 链路追踪配置
Breaker bool true 启用熔断
Shedding SheddingConf 过载降载配置

RPC 服务完整配置项

zrpc.RpcServerConf 包含的标准配置:

配置项 类型 默认值 说明
Name string 服务名称
ListenOn string 监听地址
Timeout int 2000 处理超时(毫秒)
Etcd discov.EtcdConf etcd 注册发现
Middlewares 服务端中间件
Log LogConf 日志配置
Prometheus PrometheusConf 监控配置
Telemetry TelemetryConf 链路追踪配置

RPC 客户端配置

zrpc.RpcClientConf

配置项 类型 默认值 说明
Etcd discov.EtcdConf etcd 服务发现
Endpoints []string 直连模式地址列表
Target string 目标地址(如 dns:///svc:8080
Timeout int 2000 调用超时(毫秒)
KeepAliveTime int 连接保活间隔(秒)
NonBlock bool false 非阻塞建连
MaxPoolSize int 10 连接池大小

🚨 EndpointsEtcd 二选一:直连用 Endpoints,服务发现用 Etcd。


日志配置

Log:
  ServiceName: user-api      # 服务标识
  Mode: file                 # console | file | volume
  Level: info                # debug | info | error | severe
  Path: logs/user-api        # 文件路径(Mode=file 时)
  KeepDays: 7                # 日志保留天数
  StackCooldownMillis: 100   # 相同堆栈冷却时间
  Encoding: json             # json | plain(plain 仅 Mode=console)

💡 生产环境推荐 Mode: file, Encoding: json,方便日志采集和检索。


K8s 环境配置

在 K8s 中,推荐使用 ConfigMap + Secret:

# k8s/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: user-api-config
data:
  user-api.yaml: |
    Name: user-api
    Host: 0.0.0.0
    Port: 8888
    Timeout: 3000
    UserRpc:
      Target: dns:///user-rpc.default.svc.cluster.local:8080
---
apiVersion: v1
kind: Secret
metadata:
  name: user-api-secret
type: Opaque
stringData:
  JWT_SECRET: my-secret-key
  DB_DSN: root:password@tcp(mysql:3306)/dbname

常见陷阱

陷阱 说明
🚨 Go struct 字段名与 YAML key 不一致 conf.MustLoad 按 YAML key 映射,必须对齐大小写
🚨 API 和 RPC 共用一个配置结构体 两者配置格式不同,强行共用会导致解析失败
🚨 环境变量不能覆盖嵌套字段 env tag 不支持嵌套路径,需要用扁平字段
🚨 Telemetry 配置缺失不影响启动 缺少链路追踪配置不会报错,但 trace 数据会丢失
🚨 生产环境 Mode: console 控制台日志格式不易采集,建议 file + json
🚨 MaxConns 设置过小 默认 10000 一般足够,过小会拦正常流量