go-zero/zrpc/client.go

89 lines
1.9 KiB
Go
Raw Normal View History

2020-09-18 11:41:52 +08:00
package zrpc
2020-07-26 17:09:05 +08:00
import (
"log"
"time"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/core/discov"
2020-09-18 11:41:52 +08:00
"github.com/tal-tech/go-zero/zrpc/internal"
"github.com/tal-tech/go-zero/zrpc/internal/auth"
2020-07-29 18:56:03 +08:00
"google.golang.org/grpc"
2020-07-26 17:09:05 +08:00
)
var (
WithDialOption = internal.WithDialOption
WithTimeout = internal.WithTimeout
)
type (
Client interface {
2020-09-29 16:09:11 +08:00
AddInterceptor(interceptor grpc.UnaryClientInterceptor)
Conn() *grpc.ClientConn
}
RpcClient struct {
client Client
}
)
2020-07-26 17:09:05 +08:00
func MustNewClient(c RpcClientConf, options ...internal.ClientOption) Client {
2020-07-26 17:09:05 +08:00
cli, err := NewClient(c, options...)
if err != nil {
log.Fatal(err)
}
return cli
}
func NewClient(c RpcClientConf, options ...internal.ClientOption) (Client, error) {
2020-07-29 18:06:57 +08:00
var opts []internal.ClientOption
2020-07-26 17:09:05 +08:00
if c.HasCredential() {
opts = append(opts, WithDialOption(grpc.WithPerRPCCredentials(&auth.Credential{
2020-07-26 17:09:05 +08:00
App: c.App,
Token: c.Token,
})))
}
if c.Timeout > 0 {
opts = append(opts, WithTimeout(time.Duration(c.Timeout)*time.Millisecond))
2020-07-26 17:09:05 +08:00
}
opts = append(opts, options...)
var client Client
2020-07-26 17:09:05 +08:00
var err error
2020-08-18 18:36:44 +08:00
if len(c.Endpoints) > 0 {
client, err = internal.NewClient(internal.BuildDirectTarget(c.Endpoints), opts...)
2020-07-26 17:09:05 +08:00
} else if err = c.Etcd.Validate(); err == nil {
2020-08-18 18:36:44 +08:00
client, err = internal.NewClient(internal.BuildDiscovTarget(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) (Client, error) {
2020-08-18 18:36:44 +08:00
client, err := internal.NewClient(internal.BuildDiscovTarget(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-18 18:36:44 +08:00
func NewClientWithTarget(target string, opts ...internal.ClientOption) (Client, error) {
return internal.NewClient(target, opts...)
}
2020-09-29 16:09:11 +08:00
func (rc *RpcClient) AddInterceptor(interceptor grpc.UnaryClientInterceptor) {
rc.client.AddInterceptor(interceptor)
}
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
}