go-zero/rpcx/client.go

70 lines
1.4 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package rpcx
import (
"log"
"time"
2020-07-29 18:06:57 +08:00
"zero/core/discov"
"zero/rpcx/internal"
"zero/rpcx/internal/auth"
2020-07-29 18:56:03 +08:00
"google.golang.org/grpc"
2020-07-26 17:09:05 +08:00
)
type RpcClient struct {
2020-07-29 18:06:57 +08:00
client internal.Client
2020-07-26 17:09:05 +08:00
}
2020-07-29 18:06:57 +08:00
func MustNewClient(c RpcClientConf, options ...internal.ClientOption) *RpcClient {
2020-07-26 17:09:05 +08:00
cli, err := NewClient(c, options...)
if err != nil {
log.Fatal(err)
}
return cli
}
2020-07-29 18:06:57 +08:00
func NewClient(c RpcClientConf, options ...internal.ClientOption) (*RpcClient, error) {
var opts []internal.ClientOption
2020-07-26 17:09:05 +08:00
if c.HasCredential() {
2020-07-29 18:06:57 +08:00
opts = append(opts, internal.WithDialOption(grpc.WithPerRPCCredentials(&auth.Credential{
2020-07-26 17:09:05 +08:00
App: c.App,
Token: c.Token,
})))
}
if c.Timeout > 0 {
2020-07-29 18:06:57 +08:00
opts = append(opts, internal.WithTimeout(time.Duration(c.Timeout)*time.Millisecond))
2020-07-26 17:09:05 +08:00
}
opts = append(opts, options...)
2020-07-29 18:06:57 +08:00
var client internal.Client
2020-07-26 17:09:05 +08:00
var err error
if len(c.Server) > 0 {
2020-07-29 18:06:57 +08:00
client, err = internal.NewDirectClient(c.Server, opts...)
2020-07-26 17:09:05 +08:00
} else if err = c.Etcd.Validate(); err == nil {
2020-08-06 20:55:38 +08:00
client, err = internal.NewDiscovClient(c.Etcd.Hosts, c.Etcd.Key, opts...)
2020-07-26 17:09:05 +08:00
}
if err != nil {
return nil, err
}
return &RpcClient{
client: client,
}, nil
}
func NewClientNoAuth(c discov.EtcdConf) (*RpcClient, error) {
2020-08-06 20:55:38 +08:00
client, err := internal.NewDiscovClient(c.Hosts, c.Key)
2020-07-26 17:09:05 +08:00
if err != nil {
return nil, err
}
return &RpcClient{
client: client,
}, nil
}
2020-08-06 20:55:38 +08:00
func (rc *RpcClient) Conn() *grpc.ClientConn {
return rc.client.Conn()
2020-07-26 17:09:05 +08:00
}