You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/rpcx/client.go

70 lines
1.4 KiB
Go

4 years ago
package rpcx
import (
"log"
"time"
4 years ago
"zero/core/discov"
"zero/rpcx/internal"
"zero/rpcx/internal/auth"
4 years ago
"google.golang.org/grpc"
4 years ago
)
type RpcClient struct {
4 years ago
client internal.Client
4 years ago
}
4 years ago
func MustNewClient(c RpcClientConf, options ...internal.ClientOption) *RpcClient {
4 years ago
cli, err := NewClient(c, options...)
if err != nil {
log.Fatal(err)
}
return cli
}
4 years ago
func NewClient(c RpcClientConf, options ...internal.ClientOption) (*RpcClient, error) {
var opts []internal.ClientOption
4 years ago
if c.HasCredential() {
4 years ago
opts = append(opts, internal.WithDialOption(grpc.WithPerRPCCredentials(&auth.Credential{
4 years ago
App: c.App,
Token: c.Token,
})))
}
if c.Timeout > 0 {
4 years ago
opts = append(opts, internal.WithTimeout(time.Duration(c.Timeout)*time.Millisecond))
4 years ago
}
opts = append(opts, options...)
4 years ago
var client internal.Client
4 years ago
var err error
if len(c.Server) > 0 {
4 years ago
client, err = internal.NewDirectClient(c.Server, opts...)
4 years ago
} else if err = c.Etcd.Validate(); err == nil {
client, err = internal.NewDiscovClient(c.Etcd.Hosts, c.Etcd.Key, opts...)
4 years ago
}
if err != nil {
return nil, err
}
return &RpcClient{
client: client,
}, nil
}
func NewClientNoAuth(c discov.EtcdConf) (*RpcClient, error) {
client, err := internal.NewDiscovClient(c.Hosts, c.Key)
4 years ago
if err != nil {
return nil, err
}
return &RpcClient{
client: client,
}, nil
}
func (rc *RpcClient) Conn() *grpc.ClientConn {
return rc.client.Conn()
4 years ago
}