Skip to content

Commit 904be4d

Browse files
committed
style: adjust gRPC version
1 parent a58cf01 commit 904be4d

File tree

17 files changed

+96
-64
lines changed

17 files changed

+96
-64
lines changed

internal/config/serverNameExample.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,6 @@ type App struct {
9595
type GrpcClient struct {
9696
ClientSecure ClientSecure `yaml:"clientSecure" json:"clientSecure"`
9797
ClientToken ClientToken `yaml:"clientToken" json:"clientToken"`
98-
EnableLoadBalance bool `yaml:"enableLoadBalance" json:"enableLoadBalance"`
9998
Host string `yaml:"host" json:"host"`
10099
Name string `yaml:"name" json:"name"`
101100
Port int `yaml:"port" json:"port"`

internal/rpcclient/serverNameExample.go

Lines changed: 16 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package rpcclient
22

33
import (
4-
"context"
54
"fmt"
65
"strings"
76
"sync"
@@ -41,14 +40,18 @@ func NewServerNameExampleRPCConn() {
4140
grpccli.WithEnableLog(logger.Get()),
4241
}
4342

44-
if grpcClientCfg.Timeout > 0 {
45-
cliOptions = append(cliOptions, grpccli.WithTimeout(time.Second*time.Duration(grpcClientCfg.Timeout)))
46-
}
43+
// if service discovery is not used, connect directly to the rpc service using the ip and port
44+
endpoint := fmt.Sprintf("%s:%d", grpcClientCfg.Host, grpcClientCfg.Port)
45+
isUseDiscover := false
4746

48-
// load balance
49-
if grpcClientCfg.EnableLoadBalance {
50-
cliOptions = append(cliOptions, grpccli.WithEnableLoadBalance())
51-
}
47+
// using service discovery
48+
//discoverOption, discoveryEndpoint := discoverService(cfg, grpcClientCfg)
49+
//if discoverOption != nil {
50+
// isUseDiscover = true
51+
// endpoint = discoveryEndpoint
52+
// cliOptions = append(cliOptions, discoverOption)
53+
// cliOptions = append(cliOptions, grpccli.WithEnableLoadBalance()) // load balance
54+
//}
5255

5356
// secure
5457
cliOptions = append(cliOptions, grpccli.WithSecure(
@@ -66,18 +69,6 @@ func NewServerNameExampleRPCConn() {
6669
grpcClientCfg.ClientToken.AppKey,
6770
))
6871

69-
// if service discovery is not used, connect directly to the rpc service using the ip and port
70-
endpoint := fmt.Sprintf("%s:%d", grpcClientCfg.Host, grpcClientCfg.Port)
71-
isUseDiscover := false
72-
73-
// using service discovery
74-
//grpcCliOption, discoveryEndpoint := discoverService(cfg, grpcClientCfg)
75-
//if grpcCliOption != nil {
76-
// cliOptions = append(cliOptions, grpcCliOption)
77-
// isUseDiscover = true
78-
// endpoint = discoveryEndpoint
79-
//}
80-
8172
if cfg.App.EnableTrace {
8273
cliOptions = append(cliOptions, grpccli.WithEnableTrace())
8374
}
@@ -87,6 +78,9 @@ func NewServerNameExampleRPCConn() {
8778
if cfg.App.EnableMetrics {
8879
cliOptions = append(cliOptions, grpccli.WithEnableMetrics())
8980
}
81+
if grpcClientCfg.Timeout > 0 {
82+
cliOptions = append(cliOptions, grpccli.WithTimeout(time.Second*time.Duration(grpcClientCfg.Timeout)))
83+
}
9084

9185
msg := "dial grpc server"
9286
if isUseDiscover {
@@ -95,9 +89,9 @@ func NewServerNameExampleRPCConn() {
9589
logger.Info(msg, logger.String("name", serverName), logger.String("endpoint", endpoint))
9690

9791
var err error
98-
serverNameExampleConn, err = grpccli.Dial(context.Background(), endpoint, cliOptions...)
92+
serverNameExampleConn, err = grpccli.NewClient(endpoint, cliOptions...)
9993
if err != nil {
100-
panic(fmt.Sprintf("dial rpc server failed: %v, name: %s, endpoint: %s", err, serverName, endpoint))
94+
panic(fmt.Sprintf("grpccli.NewClient error: %v, name: %s, endpoint: %s", err, serverName, endpoint))
10195
}
10296
}
10397

internal/service/service_test.go

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -38,15 +38,22 @@ func getRPCClientConnForTest(grpcClient ...config.GrpcClient) *grpc.ClientConn {
3838

3939
var cliOptions []grpccli.Option
4040

41+
endpoint := grpcClientCfg.Host + ":" + strconv.Itoa(grpcClientCfg.Port)
42+
isUseDiscover := false
43+
44+
// using service discovery
45+
//discoverOption, discoveryEndpoint := discoverService(config.Get(), grpcClientCfg)
46+
//if discoverOption != nil {
47+
// isUseDiscover = true
48+
// endpoint = discoveryEndpoint
49+
// cliOptions = append(cliOptions, discoverOption)
50+
// cliOptions = append(cliOptions, grpccli.WithEnableLoadBalance()) // load balance
51+
//}
52+
4153
if grpcClientCfg.Timeout > 0 {
4254
cliOptions = append(cliOptions, grpccli.WithTimeout(time.Second*time.Duration(grpcClientCfg.Timeout)))
4355
}
4456

45-
// load balance
46-
if grpcClientCfg.EnableLoadBalance {
47-
cliOptions = append(cliOptions, grpccli.WithEnableLoadBalance())
48-
}
49-
5057
// secure
5158
cliOptions = append(cliOptions, grpccli.WithSecure(
5259
grpcClientCfg.ClientSecure.Type,
@@ -68,24 +75,13 @@ func getRPCClientConnForTest(grpcClient ...config.GrpcClient) *grpc.ClientConn {
6875
grpccli.WithEnableLog(logger.Get()),
6976
)
7077

71-
endpoint := grpcClientCfg.Host + ":" + strconv.Itoa(grpcClientCfg.Port)
72-
isUseDiscover := false
73-
74-
// using service discovery
75-
//grpcCliOption, discoveryEndpoint := discoverService(config.Get(), grpcClientCfg)
76-
//if grpcCliOption != nil {
77-
// cliOptions = append(cliOptions, grpcCliOption)
78-
// isUseDiscover = true
79-
// endpoint = discoveryEndpoint
80-
//}
81-
8278
msg := "dialing grpc server"
8379
if isUseDiscover {
8480
msg += " with discovery from " + grpcClientCfg.RegistryDiscoveryType
8581
}
8682
logger.Info(msg, logger.String("name", grpcClientCfg.Name), logger.String("endpoint", endpoint))
8783

88-
conn, err := grpccli.Dial(context.Background(), endpoint, cliOptions...)
84+
conn, err := grpccli.NewClient(endpoint, cliOptions...)
8985
if err != nil {
9086
panic(err)
9187
}
@@ -121,9 +117,6 @@ func getGRPCClientCfg(grpcClient ...config.GrpcClient) config.GrpcClient {
121117
RegistryDiscoveryType: config.Get().App.RegistryDiscoveryType, // supports consul, etcd and nacos
122118
Name: config.Get().App.Name,
123119
}
124-
if grpcClientCfg.RegistryDiscoveryType != "" {
125-
grpcClientCfg.EnableLoadBalance = true
126-
}
127120
}
128121

129122
return grpcClientCfg

pkg/gotest/service.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ func (s *Service) GoGrpcServer() {
5959

6060
// GetClientConn dial rpc server
6161
func (s *Service) GetClientConn() *grpc.ClientConn {
62-
conn, err := grpc.Dial(s.clientAddr,
62+
conn, err := grpc.NewClient(s.clientAddr,
6363
grpc.WithTransportCredentials(insecure.NewCredentials()),
6464
)
6565
if err != nil {

pkg/grpc/client/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ Generic grpc client.
77
```go
88
import "github.com/zhufuyi/sponge/pkg/grpc/client"
99

10-
conn, err := client.Dial(context.Background(), "127.0.0.1:8282",
10+
conn, err := client.NewClient(context.Background(), "127.0.0.1:8282",
1111
//client.WithServiceDiscover(builder),
1212
//client.WithLoadBalance(),
1313
//client.WithSecure(credentials),

pkg/grpc/client/client.go

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ type options struct {
1919
credentials credentials.TransportCredentials
2020
unaryInterceptors []grpc.UnaryClientInterceptor
2121
streamInterceptors []grpc.StreamClientInterceptor
22+
dialOptions []grpc.DialOption
2223
}
2324

2425
func defaultOptions() *options {
@@ -66,8 +67,15 @@ func WithStreamInterceptor(interceptors ...grpc.StreamClientInterceptor) Option
6667
}
6768
}
6869

69-
// Dial to grpc server
70-
func Dial(ctx context.Context, endpoint string, opts ...Option) (*grpc.ClientConn, error) {
70+
// WithDialOption set DialOption
71+
func WithDialOption(dialOptions ...grpc.DialOption) Option {
72+
return func(o *options) {
73+
o.dialOptions = dialOptions
74+
}
75+
}
76+
77+
// NewClient create a new grpc client
78+
func NewClient(endpoint string, opts ...Option) (*grpc.ClientConn, error) {
7179
o := defaultOptions()
7280
o.apply(opts...)
7381

@@ -90,6 +98,11 @@ func Dial(ctx context.Context, endpoint string, opts ...Option) (*grpc.ClientCon
9098
dialOptions = append(dialOptions, grpc.WithTransportCredentials(o.credentials))
9199
}
92100

101+
// custom dial option
102+
if len(o.dialOptions) > 0 {
103+
dialOptions = append(dialOptions, o.dialOptions...)
104+
}
105+
93106
// custom unary interceptor option
94107
if len(o.unaryInterceptors) > 0 {
95108
dialOptions = append(dialOptions, grpc.WithChainUnaryInterceptor(o.unaryInterceptors...))
@@ -100,5 +113,10 @@ func Dial(ctx context.Context, endpoint string, opts ...Option) (*grpc.ClientCon
100113
dialOptions = append(dialOptions, grpc.WithChainStreamInterceptor(o.streamInterceptors...))
101114
}
102115

103-
return grpc.DialContext(ctx, endpoint, dialOptions...)
116+
return grpc.NewClient(endpoint, dialOptions...)
117+
}
118+
119+
// Dial to grpc server
120+
func Dial(_ context.Context, endpoint string, opts ...Option) (*grpc.ClientConn, error) {
121+
return NewClient(endpoint, opts...)
104122
}

pkg/grpc/client/client_test.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,14 @@ var streamInterceptors = []grpc.StreamClientInterceptor{
3232
},
3333
}
3434

35-
func TestDial(t *testing.T) {
36-
conn, err := Dial(context.Background(), "127.0.0.1:50082",
35+
func TestNewClient(t *testing.T) {
36+
conn, err := NewClient("127.0.0.1:50082",
3737
WithServiceDiscover(new(builder)),
3838
WithLoadBalance(),
3939
WithSecure(insecure.NewCredentials()),
4040
WithUnaryInterceptor(unaryInterceptors...),
4141
WithStreamInterceptor(streamInterceptors...),
42+
WithDialOption(grpc.WithDefaultServiceConfig(`{"loadBalancingConfig": [{"round_robin":{}}]}`)),
4243
)
4344
defer conn.Close()
4445
t.Log(conn, err)

pkg/grpc/grpccli/dail.go

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@ import (
1515
"github.com/zhufuyi/sponge/pkg/servicerd/discovery"
1616
)
1717

18-
// Dial to grpc server
19-
func Dial(ctx context.Context, endpoint string, opts ...Option) (*grpc.ClientConn, error) {
18+
// NewClient creates a new grpc client
19+
func NewClient(endpoint string, opts ...Option) (*grpc.ClientConn, error) {
2020
o := defaultOptions()
2121
o.apply(opts...)
2222

@@ -59,7 +59,13 @@ func Dial(ctx context.Context, endpoint string, opts ...Option) (*grpc.ClientCon
5959
// custom options
6060
clientOptions = append(clientOptions, o.dialOptions...)
6161

62-
return grpc.DialContext(ctx, endpoint, clientOptions...)
62+
return grpc.NewClient(endpoint, clientOptions...)
63+
}
64+
65+
// Dial to grpc server
66+
// Deprecated: use NewClient instead
67+
func Dial(_ context.Context, endpoint string, opts ...Option) (*grpc.ClientConn, error) {
68+
return NewClient(endpoint, opts...)
6369
}
6470

6571
func secureOption(o *options) (grpc.DialOption, error) {

pkg/grpc/grpccli/dail_test.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,15 @@ import (
1313
"github.com/zhufuyi/sponge/pkg/servicerd/registry/etcd"
1414
)
1515

16-
func TestDial(t *testing.T) {
17-
_, err := Dial(context.Background(), "localhost:8282")
16+
func TestNewClient(t *testing.T) {
17+
_, err := NewClient("localhost:8282")
18+
assert.NoError(t, err)
19+
_, err = Dial(context.Background(), "localhost:8282")
1820
assert.NoError(t, err)
1921
}
2022

21-
func TestDial2(t *testing.T) {
22-
_, err := Dial(context.Background(), "localhost:8282",
23+
func TestNewClient2(t *testing.T) {
24+
_, err := NewClient("localhost:8282",
2325
WithEnableLog(zap.NewNop()),
2426
WithEnableMetrics(),
2527
WithToken(true, "grpc", "123456"),

pkg/grpc/gtls/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ func main() {
3838
)
3939
// check err
4040

41-
conn, err := grpc.Dial("127.0.0.1:8080", grpc.WithTransportCredentials(credentials))
41+
conn, err := grpc.NewClient("127.0.0.1:8080", grpc.WithTransportCredentials(credentials))
4242
// check err
4343
}
4444
```
@@ -82,7 +82,7 @@ func main() {
8282
)
8383
// check err
8484

85-
conn, err := grpc.Dial("127.0.0.1:8080", grpc.WithTransportCredentials(credentials))
85+
conn, err := grpc.NewClient("127.0.0.1:8080", grpc.WithTransportCredentials(credentials))
8686
// check err
8787
}
8888
```

0 commit comments

Comments
 (0)