github.com/lingyao2333/mo-zero@v1.4.1/zrpc/config.go (about) 1 package zrpc 2 3 import ( 4 "github.com/lingyao2333/mo-zero/core/discov" 5 "github.com/lingyao2333/mo-zero/core/service" 6 "github.com/lingyao2333/mo-zero/core/stores/redis" 7 "github.com/lingyao2333/mo-zero/zrpc/resolver" 8 ) 9 10 type ( 11 // A RpcServerConf is a rpc server config. 12 RpcServerConf struct { 13 service.ServiceConf 14 ListenOn string 15 Etcd discov.EtcdConf `json:",optional,inherit"` 16 Auth bool `json:",optional"` 17 Redis redis.RedisKeyConf `json:",optional"` 18 StrictControl bool `json:",optional"` 19 // setting 0 means no timeout 20 Timeout int64 `json:",default=2000"` 21 CpuThreshold int64 `json:",default=900,range=[0:1000]"` 22 // grpc health check switch 23 Health bool `json:",default=true"` 24 } 25 26 // A RpcClientConf is a rpc client config. 27 RpcClientConf struct { 28 Etcd discov.EtcdConf `json:",optional,inherit"` 29 Endpoints []string `json:",optional"` 30 Target string `json:",optional"` 31 App string `json:",optional"` 32 Token string `json:",optional"` 33 NonBlock bool `json:",optional"` 34 Timeout int64 `json:",default=2000"` 35 } 36 ) 37 38 // NewDirectClientConf returns a RpcClientConf. 39 func NewDirectClientConf(endpoints []string, app, token string) RpcClientConf { 40 return RpcClientConf{ 41 Endpoints: endpoints, 42 App: app, 43 Token: token, 44 } 45 } 46 47 // NewEtcdClientConf returns a RpcClientConf. 48 func NewEtcdClientConf(hosts []string, key, app, token string) RpcClientConf { 49 return RpcClientConf{ 50 Etcd: discov.EtcdConf{ 51 Hosts: hosts, 52 Key: key, 53 }, 54 App: app, 55 Token: token, 56 } 57 } 58 59 // HasEtcd checks if there is etcd settings in config. 60 func (sc RpcServerConf) HasEtcd() bool { 61 return len(sc.Etcd.Hosts) > 0 && len(sc.Etcd.Key) > 0 62 } 63 64 // Validate validates the config. 65 func (sc RpcServerConf) Validate() error { 66 if !sc.Auth { 67 return nil 68 } 69 70 return sc.Redis.Validate() 71 } 72 73 // BuildTarget builds the rpc target from the given config. 74 func (cc RpcClientConf) BuildTarget() (string, error) { 75 if len(cc.Endpoints) > 0 { 76 return resolver.BuildDirectTarget(cc.Endpoints), nil 77 } else if len(cc.Target) > 0 { 78 return cc.Target, nil 79 } 80 81 if err := cc.Etcd.Validate(); err != nil { 82 return "", err 83 } 84 85 if cc.Etcd.HasAccount() { 86 discov.RegisterAccount(cc.Etcd.Hosts, cc.Etcd.User, cc.Etcd.Pass) 87 } 88 if cc.Etcd.HasTLS() { 89 if err := discov.RegisterTLS(cc.Etcd.Hosts, cc.Etcd.CertFile, cc.Etcd.CertKeyFile, 90 cc.Etcd.CACertFile, cc.Etcd.InsecureSkipVerify); err != nil { 91 return "", err 92 } 93 } 94 95 return resolver.BuildDiscovTarget(cc.Etcd.Hosts, cc.Etcd.Key), nil 96 } 97 98 // HasCredential checks if there is a credential in config. 99 func (cc RpcClientConf) HasCredential() bool { 100 return len(cc.App) > 0 && len(cc.Token) > 0 101 }