rpc配置控制着一个rpc服务的各种功能,包含但不限于监听地址,etcd配置,超时,熔断配置等,下面我们以一个常见的rpc服务配置来进行说明。
配置说明
Config struct {zrpc.RpcServerConfCacheRedis cache.CacheConf // redis缓存配置,详情见api配置说明,这里不赘述Mysql struct { // mysql数据库访问配置,详情见api配置说明,这里不赘述DataSource string}}
zrpc.RpcServerConf
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 automaticallyTimeout int64 `json:",default=2000"` // 超时控制,单位:毫秒CpuThreshold int64 `json:",default=900,range=[0:1000]"` cpu降载阈值,默认900,可允许设置范围0到1000}
discov.EtcdConf
type EtcdConf struct {Hosts []string // etcd host数组Key string // rpc注册key}
redis.RedisKeyConf
RedisConf struct {Host string // redis 主机Type string `json:",default=node,options=node|cluster"` // redis类型Pass string `json:",optional"` // redis密码}RedisKeyConf struct {RedisConfKey string `json:",optional"` // 验证key}
Rpc示例
配置信息
D:\Projects\Github\NoobWu\go-zero-demo\book\service\user\cmd\rpc\etc\user.yaml
Name: user.rpc#rpc监听地址和端口,如:127.0.0.1:8888ListenOn: 127.0.0.1:8080#etcd相关配置Etcd:#etcd host数组Hosts:- 127.0.0.1:2379# rpc注册keyKey: user.rpc#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
D:\Projects\Github\NoobWu\go-zero-demo\book\service\user\cmd\rpc\user.go
// Code generated by goctl. DO NOT EDIT!// Source: user.protopackage mainimport ("flag""fmt""go-zero-demo/book/service/user/cmd/rpc/internal/config""go-zero-demo/book/service/user/cmd/rpc/internal/server""go-zero-demo/book/service/user/cmd/rpc/internal/svc""go-zero-demo/book/service/user/cmd/rpc/user""github.com/tal-tech/go-zero/core/conf""github.com/tal-tech/go-zero/zrpc""google.golang.org/grpc")var configFile = flag.String("f", "etc/user.yaml", "the config file")func main() {flag.Parse()var c config.Configconf.MustLoad(*configFile, &c) //读取配置文件信息ctx := svc.NewServiceContext(c)srv := server.NewUserServer(ctx)s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {user.RegisterUserServer(grpcServer, srv)})defer s.Stop()fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)s.Start()}
启动Rpc服务
PS D:\Projects\Github\NoobWu\go-zero-demo\book\service\user\cmd\rpc> go run .\user.go -f .\etc\user.yaml
项目源代码
https://github.com/noobwu/go-zero-demo/tree/master/book/service/user/cmd/rpc
PS D:\Projects\Github\NoobWu\go-zero-demo\book\service\user\cmd\rpc> tree /f.│ user.go│ user.proto│├─etc│ user.yaml│├─internal│ ├─config│ │ config.go│ ││ ├─logic│ │ getuserlogic.go│ ││ ├─server│ │ userserver.go│ ││ └─svc│ servicecontext.go│├─user│ user.pb.go│└─userclientuser.go

