api配置控制着api服务中的各种功能,包含但不限于服务监听地址,端口,环境配置,日志配置等,下面我们从一个简单的配置来看一下api中常用配置分别有什么作用。
配置说明
通过yaml配置我们会发现,有很多参数我们并没有于config对齐,这是因为config定义中,有很多都是带optional或者default 标签的,对于optional可选项,你可以根据自己需求判断是否需要设置,对于default标签,如果你觉得默认值就已经够了,可以不用设置, 一般default中的值基本不用修改,可以认为是最佳实践值。
Config
go-zero-demo\greet\etc\greet-api.yaml
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配置}
rest.RestConf
api服务基础配置,包含监听地址,监听端口,证书配置,限流,熔断参数,超时参数等控制,对其展开我们可以看到:
service.ServiceConf // service配置Host string `json:",default=0.0.0.0"` // http监听ip,默认0.0.0.0Port int // http监听端口,必填CertFile string `json:",optional"` // https证书文件,可选KeyFile string `json:",optional"` // https私钥文件,可选Verbose bool `json:",optional"` // 是否打印详细http请求日志MaxConns int `json:",default=10000"` // http同时可接受最大请求数(限流数),默认10000MaxBytes int64 `json:",default=1048576,range=[0:8388608]"` // http可接受请求的最大ContentLength,默认1048576,被设置值不能必须在0到8388608之间// millisecondsTimeout int64 `json:",default=3000"` // 超时时长控制,单位:毫秒,默认3000CpuThreshold int64 `json:",default=900,range=[0:1000]"` // cpu降载阈值,默认900,可允许设置范围0到1000Signature SignatureConf `json:",optional"` // 签名配置
service.ServiceConf
type ServiceConf struct {Name string // 服务名称Log logx.LogConf // 日志配置Mode string `json:",default=pro,options=dev|test|pre|pro"` // 服务环境,dev-开发环境,test-测试环境,pre-预发环境,pro-正式环境MetricsUrl string `json:",optional"` // 指标上报接口地址,该地址需要支持post json即可Prometheus prometheus.Config `json:",optional"` // prometheus配置}
logx.LogConf
type LogConf struct {ServiceName string `json:",optional"` // 服务名称Mode string `json:",default=console,options=console|file|volume"` // 日志模式,console-输出到console,file-输出到当前服务器(容器)文件,,volume-输出docker挂在文件内Path string `json:",default=logs"` // 日志存储路径Level string `json:",default=info,options=info|error|severe"` // 日志级别Compress bool `json:",optional"` // 是否开启gzip压缩KeepDays int `json:",optional"` // 日志保留天数StackCooldownMillis int `json:",default=100"` // 日志write间隔}
prometheus.Config
type Config struct {Host string `json:",optional"` // prometheus 监听hostPort int `json:",default=9101"` // prometheus 监听端口Path string `json:",default=/metrics"` // 上报地址}
SignatureConf
SignatureConf struct {Strict bool `json:",default=false"` // 是否Strict模式,如果是则PrivateKeys必填Expiry time.Duration `json:",default=1h"` // 有效期,默认1小时PrivateKeys []PrivateKeyConf // 签名密钥相关配置}
PrivateKeyConf
PrivateKeyConf struct {Fingerprint string // 指纹配置KeyFile string // 密钥配置}
cache.CacheConf
ClusterConf []NodeConfNodeConf struct {redis.RedisConfWeight int `json:",default=100"` // 权重}
redis.RedisConf
RedisConf struct {Host string // redis地址Type string `json:",default=node,options=node|cluster"` // redis类型Pass string `json:",optional"` // redis密码}ya
Api示例
配置信息
D:\Projects\Github\NoobWu\go-zero-demo\book\service\user\cmd\api\etc\user-api.yaml
Name: user-api#http监听ip,默认0.0.0.0Host: 0.0.0.0#http监听端口,必填Port: 8888#是否打印详细http请求日志Verbose: true#http同时可接受最大请求数(限流数),默认10000MaxConns: 10#http可接受请求的最大ContentLength,默认1048576,被设置值不能必须在0到8388608之间MaxBytes: 1048576#超时时长控制,单位:毫秒,默认3000Timeout: 3000#cpu降载阈值,默认900,可允许设置范围0到1000CpuThreshold: 900#mysql链接地址,满足 $user:$password@tcp($ip:$port)/$db?$queries 格式即可Mysql:DataSource: root:123456@tcp(127.0.0.1:3306)/gozero?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai#缓存相关设置CacheRedis:- Host: 127.0.0.1:6379Pass:Type: node#认证相关设置Auth:AccessSecret: ad879037-c7a4-4063-9236-6bfc35d54b7dAccessExpire: 86400
D:\Projects\Github\NoobWu\go-zero-demo\book\service\user\cmd\api\user.go
package mainimport ("flag""fmt""net/http""go-zero-demo/book/common/errorx""go-zero-demo/book/service/user/cmd/api/internal/config""go-zero-demo/book/service/user/cmd/api/internal/handler""go-zero-demo/book/service/user/cmd/api/internal/svc""github.com/tal-tech/go-zero/core/conf""github.com/tal-tech/go-zero/rest""github.com/tal-tech/go-zero/rest/httpx")var configFile = flag.String("f", "etc/user-api.yaml", "the config file")func main() {flag.Parse()var c config.Configconf.MustLoad(*configFile, &c) //读取配置信息ctx := svc.NewServiceContext(c)server := rest.MustNewServer(c.RestConf)defer server.Stop()handler.RegisterHandlers(server, ctx)// 自定义错误httpx.SetErrorHandler(func(err error) (int, interface{}) {switch e := err.(type) {case *errorx.CodeError:return http.StatusOK, e.Data()default:return http.StatusInternalServerError, nil}})fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)server.Start()}
PS D:\Projects\Github\NoobWu\go-zero-demo\book\service\user\cmd\api> go run .\user.go -f .\etc\user-api.yaml


