go-zero 基础 -- 配置
创始人
2025-06-01 20:57:08

1、api配置

api配置控制着api服务中的各种功能,包含但不限于服务监听地址,端口,环境配置,日志配置等,下面我们从一个简单的配置来看一下api中常用配置分别有什么作用。

1.1 配置说明

通过yaml配置我们会发现,有很多参数我们并没有与config对齐,这是因为config定义中,有很多都是带optional或者default 标签的,对于optional可选项,你可以根据自己需求判断是否需要设置,对于default标签,如果你觉得默认值就已经够了,可以不用设置, 一般default中的值基本不用修改,可以认为是最佳实践值。

Config

type Config struct{rest.RestConf // rest api配置Auth struct { // jwt鉴权配置AccessSecret string // jwt密钥AccessExpire int64 // 有效期,单位:秒}Mysql struct { // 数据库配置,除mysql外,可能还有mongo等其他数据库DataSource string // mysql链接地址,满足 $user:$password@tcp($ip:$port)/$db?$queries 格式即可}CacheRedis cache.CacheConf // redis缓存UserRpc    zrpc.RpcClientConf // rpc client配置
}    

1.2 rest.RestConf

api服务基础配置,包含监听地址监听端口证书配置限流熔断参数超时参数等控制,对其展开我们可以看到:

	// A RestConf is a http service config.// Why not name it as Conf, because we need to consider usage like://  type Config struct {//     zrpc.RpcConf//     rest.RestConf//  }// if with the name Conf, there will be two Conf inside Config.RestConf struct {service.ServiceConfHost     string `json:",default=0.0.0.0"`Port     intCertFile string `json:",optional"`KeyFile  string `json:",optional"`Verbose  bool   `json:",optional"`MaxConns int    `json:",default=10000"`MaxBytes int64  `json:",default=1048576"`// millisecondsTimeout      int64         `json:",default=3000"`CpuThreshold int64         `json:",default=900,range=[0:1000]"`Signature    SignatureConf `json:",optional"`// There are default values for all the items in Middlewares.Middlewares MiddlewaresConf// TraceIgnorePaths is paths blacklist for trace middleware.TraceIgnorePaths []string `json:",optional"`}

1.2.1 service.ServiceConf

// A ServiceConf is a service config.
type ServiceConf struct {Name       stringLog        logx.LogConfMode       string `json:",default=pro,options=dev|test|rt|pre|pro"`MetricsUrl string `json:",optional"`// Deprecated: please use DevServerPrometheus prometheus.Config `json:",optional"`Telemetry  trace.Config      `json:",optional"`DevServer  devserver.Config  `json:",optional"`
}

logx.LogConf

// A LogConf is a logging config.
type LogConf struct {ServiceName string `json:",optional"` // 服务名称// Mode represents the logging mode, default is `console`.// console: log to console.// file: log to file.// volume: used in k8s, prepend the hostname to the log file name.Mode string `json:",default=console,options=[console,file,volume]"`// Encoding represents the encoding type, default is `json`.// json: json encoding.// plain: plain text encoding, typically used in development.Encoding string `json:",default=json,options=[json,plain]"`// TimeFormat represents the time format, default is `2006-01-02T15:04:05.000Z07:00`.TimeFormat string `json:",optional"`// Path represents the log file path, default is `logs`.Path string `json:",default=logs"`// Level represents the log level, default is `info`.Level string `json:",default=info,options=[debug,info,error,severe]"`// MaxContentLength represents the max content bytes, default is no limit.MaxContentLength uint32 `json:",optional"`// Compress represents whether to compress the log file, default is `false`.// 是否开启gzip压缩Compress bool `json:",optional"`// Stdout represents whether to log statistics, default is `true`.Stat bool `json:",default=true"`// KeepDays represents how many days the log files will be kept. Default to keep all files.// Only take effect when Mode is `file` or `volume`, both work when Rotation is `daily` or `size`.KeepDays int `json:",optional"`// StackCooldownMillis represents the cooldown time for stack logging, default is 100ms.// 日志write间隔StackCooldownMillis int `json:",default=100"`// MaxBackups represents how many backup log files will be kept. 0 means all files will be kept forever.// Only take effect when RotationRuleType is `size`.// Even thougth `MaxBackups` sets 0, log files will still be removed// if the `KeepDays` limitation is reached.MaxBackups int `json:",default=0"`// MaxSize represents how much space the writing log file takes up. 0 means no limit. The unit is `MB`.// Only take effect when RotationRuleType is `size`MaxSize int `json:",default=0"`// RotationRuleType represents the type of log rotation rule. Default is `daily`.// daily: daily rotation.// size: size limited rotation.Rotation string `json:",default=daily,options=[daily,size]"`
}

prometheus.Config

type Config struct {Host string `json:",optional"` // prometheus 监听hostPort int    `json:",default=9101"` // prometheus 监听端口Path string `json:",default=/metrics"` // 上报地址
}

1.2.2 SignatureConf

type SignatureConf struct {Strict      bool          `json:",default=false"` // 是否Strict模式,如果是则PrivateKeys必填Expiry      time.Duration `json:",default=1h"` // 有效期,默认1小时PrivateKeys []PrivateKeyConf // 签名密钥相关配置
}

PrivateKeyConf

type PrivateKeyConf struct {Fingerprint string // 指纹配置KeyFile     string // 密钥配置
}

1.3 cache.CacheConf

type CacheConf struct{ClusterConf []NodeConfNodeConf struct {redis.RedisConfWeight int `json:",default=100"` // 权重}
}

redis.RedisConf

type RedisConf struct {Host string // redis地址Type string `json:",default=node,options=node|cluster"` // redis类型Pass string `json:",optional"` // redis密码
}

2、rpc配置

rpc配置控制着一个rpc服务的各种功能,包含但不限于监听地址etcd配置超时熔断配置等,下面我们以一个常见的rpc服务配置来进行说明。

2.1 配置说明

type Config struct {zrpc.RpcServerConfCacheRedis         cache.CacheConf // redis缓存配置,详情见api配置说明,这里不赘述Mysql struct { // mysql数据库访问配置,详情见api配置说明,这里不赘述DataSource string}
}

2.1 zrpc.RpcServerConf

type RpcServerConf struct {service.ServiceConf // 服务配置,详情见api配置说明,这里不赘述ListenOn      string // rpc监听地址和端口,如:127.0.0.1:8888Etcd          discov.EtcdConf    `json:",optional"` // etcd相关配置Auth          bool               `json:",optional"` // 是否开启Auth,如果是则Redis为必填Redis         redis.RedisKeyConf `json:",optional"` // Auth验证StrictControl bool               `json:",optional"` // 是否Strict模式,如果是则遇到错误是Auth失败,否则可以认为成功// pending forever is not allowed// never set it to 0, if zero, the underlying will set to 2s automatically// 不允许永久挂起// 超时控制,单位:毫秒Timeout      int64 `json:",default=2000"` // cpu降载阈值,默认900,可允许设置范围0到1000CpuThreshold int64 `json:",default=900,range=[0:1000]"` 
}

discov.EtcdConf

type EtcdConf struct {Hosts []string // etcd host数组Key   string // rpc注册key
}

redis.RedisKeyConf

type RedisConf struct {Host string // redis 主机Type string `json:",default=node,options=node|cluster"` // redis类型Pass string `json:",optional"` // redis密码
}type RedisKeyConf struct {RedisConfKey string `json:",optional"` // 验证key
}

相关内容

热门资讯

宜宾名酒博览会开幕,将持续至明... 🍷 你是否知道,在享受美酒的同时,也能兼顾健康? 随着2025中国国际名酒博览会的开幕,来自全球...
传承人齐诵《五粮九训》、再现千... 12月17日清晨,当第一缕晨曦掠过五粮液酒圣山山巅,一声雄浑的号角划破长空,五粮液第二十九届祭祀大典...
2025中国国际名酒博览会在宜... 12月19日上午,四川宜宾,合江门前,高朋满座。由中国轻工业联合会指导,中国酒业协会、四川省酒业协会...
美食故事:从红烧肉到路边摊,背... 在一家规模不算大的食肆背后,说不定潜藏着几代人的迁移过程;于一道平常菜系之中,或许封存着一个时代的共...
宣城的美食有哪些,有什么特点呢 宣城,这座位于安徽东南部的城市,不仅自然风光秀丽,而且美食文化源远流长。当地美食融合了徽菜的传统风味...