package client import ( "git.ichub.com/general/webcli120/goconfig/base/basedto" "git.ichub.com/general/webcli120/goconfig/gogrpc/gorpcclient" proto "website-grpc/gorpc/proto/hello" websiteproto "website-grpc/gorpc/proto/website" ) const RPC_SERVER_NAME = "gorpc.website.com" type RpcFacade struct { basedto.BaseEntitySingle RPC_SERVER_NAME string HelloService *gorpcclient.GorpcCli[proto.HelloYeahService] WebsiteService *gorpcclient.GorpcCli[websiteproto.WebsiteService] } func NewRpcFacade() *RpcFacade { var f = &RpcFacade{ RPC_SERVER_NAME: RPC_SERVER_NAME, } f.Init() return f } func (self *RpcFacade) Init() { self.HelloService = gorpcclient.NewGorpcCli(self.RPC_SERVER_NAME, proto.NewHelloYeahService) self.WebsiteService = gorpcclient.NewGorpcCli(self.RPC_SERVER_NAME, websiteproto.NewWebsiteService) } 测试
package gorpcclient import ( "git.ichub.com/general/webcli120/goconfig/gogrpc/common" "github.com/micro/go-micro/v2/client" "github.com/sirupsen/logrus" "sync" )
func Test001_helloSayhello(t *testing.T) { var req = &protoHello.HelloRequest{} req.Age = 46 req.Name = "leijmdas@163.com" ctx, _ := context.WithTimeout(context.Background(), 30*time.Second) var meta = gometadata.FindBeanIchubMetadata() meta.Data = ichubconfig.FindBeanIchubConfig().ReadIchubWebServer() ctx = gometadata.FindBeanGoMetadata().Set(ctx, meta) var res, err = FindBeanRpcFacade().HelloService.RpcClient().SayHello(ctx, req) logrus.Info(err, basemodel.AdapterFrom(res)) }
INFO[2024-11-1126 22:23:29]C:/Users/admin/go/pkg/mod/git.ichub.com/general/webcli120@v1.0.994-dev-05/goconfig/basedi/bean_info.go:25 git.ichub.com/general/webcli120/goconfig/basedi.(*BeanInfo).CreateBean() you new a single bean :RpcFacade
INFO[2024-11-1126 22:23:29]D:/gitlab.ichub.com/general-website/website-grpc/gorpc/client/rpc_facade_test.go:29 website-grpc/gorpc/client.Test001_helloSayhello() <nil> {
"msg": "46",
"msg2": "leijmdas@163.com"
}
--- PASS: Test001_helloSayhello (0.06s)
实现细节
type GorpcCli[S any] struct { rpcClient S RpcServiceName string FuncNew func(name string, c client.Client) S } func (g *GorpcCli[S]) RpcClient() S { return g.rpcClient } func DefaultOf[S any](rpcServiceName string, funcNew func(name string, c client.Client) S) *GorpcCli[S] { var rpcli = Default[S](rpcServiceName) rpcli.init(funcNew) return rpcli } func NewGorpcCli[S any](rpcServiceName string, funcNew func(name string, c client.Client) S) *GorpcCli[S] { return DefaultOf[S](rpcServiceName, funcNew) } func Default[S any](rpcServiceName string) *GorpcCli[S] { return &GorpcCli[S]{ RpcServiceName: rpcServiceName, } } func (g *GorpcCli[S]) init(funcNew func(name string, c client.Client) S) *GorpcCli[S] { if common.Client() == nil { logrus.Error("client is nil") return nil } g.rpcClient = funcNew(g.RpcServiceName, *common.Client()) return g } func (g *GorpcCli[S]) SetRpcClient(rpcClient S) { g.rpcClient = rpcClient }标签:return,string,CLIENT,client,RPC,GorpcCli,func,GO,com From: https://blog.csdn.net/leijmdas/article/details/144069677