Skip to content

Commit be000b3

Browse files
committed
feat:add rpc client factory model
1 parent 29e6422 commit be000b3

File tree

2 files changed

+55
-9
lines changed

2 files changed

+55
-9
lines changed

app/shop/custom/internal/data/data.go

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package data
2+
3+
type DataFactory interface {
4+
Users() UserData
5+
}

app/shop/custom/internal/data/rpc/rpc.go

+50-9
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,25 @@ import (
44
"github.com/coderi421/gframework/gmicro/registry"
55
"github.com/coderi421/gframework/gmicro/registry/consul"
66
"github.com/coderi421/gframework/pkg/errors"
7+
upb "github.com/coderi421/goshop/api/user/v1"
78
"github.com/coderi421/goshop/app/pkg/code"
89
"github.com/coderi421/goshop/app/pkg/options"
910
"github.com/coderi421/goshop/app/shop/custom/internal/data"
1011
consulAPI "github.com/hashicorp/consul/api"
12+
"sync"
13+
)
14+
15+
type grpcData struct {
16+
uc upb.UserClient
17+
}
18+
19+
func (g *grpcData) Users() data.UserData {
20+
return NewUsers(g.uc)
21+
}
22+
23+
var (
24+
rpcFactory data.DataFactory
25+
once sync.Once
1126
)
1227

1328
// NewDiscovery 目前是基于consul实现的 以后想换成nocos etcd等 可以直接在这换
@@ -23,16 +38,42 @@ func NewDiscovery(opts *options.RegistryOptions) (registry.Discovery, error) {
2338
}
2439

2540
// GetDataFactoryOr rpc的连接,基于服务发现
26-
func GetDataFactoryOr(options *options.RegistryOptions) (data.UserData, error) {
27-
//这里负责依赖所有的rpc连接
28-
discovery, err := NewDiscovery(options)
29-
if err != nil {
30-
return nil, err
41+
func GetDataFactoryOr(options *options.RegistryOptions) (data.DataFactory, error) {
42+
var (
43+
discovery registry.Discovery
44+
userClient upb.UserClient
45+
errOnce error
46+
once sync.Once
47+
)
48+
49+
if options == nil && rpcFactory == nil {
50+
return nil, errors.WithCode(code.ErrInit, "init Data Factory error: options is nil")
3151
}
32-
userClient, err := NewUserServiceClient(discovery)
33-
if err != nil {
34-
return nil, err
52+
// 单利模式
53+
once.Do(func() {
54+
var err error
55+
//这里负责依赖所有的rpc连接
56+
discovery, err = NewDiscovery(options)
57+
if err != nil {
58+
errOnce = err
59+
return
60+
}
61+
62+
//实例 user rpc client
63+
userClient, err = NewUserServiceClient(discovery)
64+
if err != nil {
65+
errOnce = err
66+
return
67+
}
68+
69+
rpcFactory = &grpcData{
70+
uc: userClient,
71+
}
72+
})
73+
74+
if rpcFactory == nil || errOnce != nil {
75+
return nil, errors.WithCode(code.ErrConnectGRPC, "failed to get rpc store factory %s", errOnce.Error())
3576
}
3677

37-
return NewUsers(userClient), nil
78+
return rpcFactory, nil
3879
}

0 commit comments

Comments
 (0)