proto/goutils/proto_build/tpls/auto_grpc_nacos.tpl
huangsimin@fusen.cn a5165828ba 更新grpc
2024-01-25 17:04:41 +08:00

103 lines
2.4 KiB
Smarty

package {{.PackageName}}
import (
"context"
"fmt"
"log"
"reflect"
"fusen-basic/env"
"github.com/nacos-group/nacos-sdk-go/v2/clients/naming_client"
"github.com/nacos-group/nacos-sdk-go/v2/vo"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
var namingClient naming_client.INamingClient
var groupName string
func init() {
AutoGrpcInit(env.StartAutoGrpc())
}
// AutoGrpcInit auto grpc 必须调用初始化
func AutoGrpcInit(obj any) {
value := reflect.ValueOf(obj)
if value.Kind() == reflect.Ptr {
value = value.Elem()
}
groupName = value.FieldByName("GroupName").String()
for i := 0; i < value.NumField(); i++ {
v := value.Field(i)
if v.IsValid() {
_namingClient, ok := v.Interface().(naming_client.INamingClient)
if ok {
namingClient = _namingClient
}
}
}
}
{{range .ClientParams}}
func Auto{{.ClientName}}Client(ctx context.Context) {{.ClientName}}Client {
if namingClient == nil {
log.Println("nameClient must be init. call")
return nil
}
sel := vo.SelectOneHealthInstanceParam{
ServiceName: "{{.GrpcServiceName}}",
GroupName: groupName,
}
for i := 0; i < 3; i++ {
insService, err := namingClient.SelectOneHealthyInstance(sel)
if err != nil {
log.Println(err)
continue
}
if insService.Enable && insService.Healthy {
conn, err := grpc.DialContext(ctx, fmt.Sprintf("%s:%d", insService.Ip, insService.Port), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Println(err)
continue
}
return New{{.ClientName}}Client(conn)
}
}
log.Println(fmt.Errorf("no healthy with times 3"))
return nil
}
func Auto{{.ClientName}}ClientEx(ctx context.Context, opts ...grpc.DialOption) ({{.ClientName}}Client,error) {
if namingClient == nil {
return nil, fmt.Errorf("nameClient must be init. call")
}
sel := vo.SelectOneHealthInstanceParam{
ServiceName: "{{.GrpcServiceName}}",
GroupName: groupName,
}
for i := 0; i < 3; i++ {
insService, err := namingClient.SelectOneHealthyInstance(sel)
if err != nil {
log.Println(err)
continue
}
if insService.Enable && insService.Healthy {
conn, err := grpc.DialContext(ctx, fmt.Sprintf("%s:%d", insService.Ip, insService.Port), opts...)
if err != nil {
log.Println(err)
continue
}
return New{{.ClientName}}Client(conn), nil
}
}
return nil, fmt.Errorf("no healthy with times 3")
}
{{end}}