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 < 10; i++ { insService, err := namingClient.SelectOneHealthyInstance(sel) if err != nil { log.Println(err) return nil } 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) return nil } return New{{.ClientName}}Client(conn) } } 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 < 10; i++ { insService, err := namingClient.SelectOneHealthyInstance(sel) if err != nil { return nil, err } if insService.Enable && insService.Healthy { conn, err := grpc.DialContext(ctx, fmt.Sprintf("%s:%d", insService.Ip, insService.Port), opts...) if err != nil { return nil, err } return New{{.ClientName}}Client(conn), nil } } return nil, fmt.Errorf("no healthy with times 10") } {{end}}