proto/goutils/proto_build/tpls/auto_grpc_nacos.tpl

103 lines
2.4 KiB
Smarty
Raw Normal View History

2023-11-27 09:36:02 +00:00
package {{.PackageName}}
import (
"context"
"fmt"
"log"
"reflect"
"fusen-basic/env"
2023-11-27 09:36:02 +00:00
"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())
}
2023-11-27 09:36:02 +00:00
// AutoGrpcInit auto grpc 必须调用初始化
func AutoGrpcInit(obj any) {
value := reflect.ValueOf(obj)
if value.Kind() == reflect.Ptr {
value = value.Elem()
}
2024-01-18 09:02:13 +00:00
groupName = value.FieldByName("GroupName").String()
2023-11-27 09:36:02 +00:00
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,
}
2024-01-25 09:04:41 +00:00
for i := 0; i < 3; i++ {
2024-01-19 08:23:47 +00:00
insService, err := namingClient.SelectOneHealthyInstance(sel)
if err != nil {
log.Println(err)
2024-01-25 09:04:41 +00:00
continue
2024-01-19 08:23:47 +00:00
}
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)
2024-01-25 09:04:41 +00:00
continue
2024-01-19 08:23:47 +00:00
}
return New{{.ClientName}}Client(conn)
}
2023-11-27 09:36:02 +00:00
}
2024-01-25 09:04:41 +00:00
log.Println(fmt.Errorf("no healthy with times 3"))
2024-01-19 08:23:47 +00:00
return nil
2023-11-27 09:36:02 +00:00
}
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,
}
2024-01-25 09:04:41 +00:00
for i := 0; i < 3; i++ {
2024-01-19 08:23:47 +00:00
insService, err := namingClient.SelectOneHealthyInstance(sel)
if err != nil {
2024-01-25 09:04:41 +00:00
log.Println(err)
continue
2024-01-19 08:23:47 +00:00
}
if insService.Enable && insService.Healthy {
conn, err := grpc.DialContext(ctx, fmt.Sprintf("%s:%d", insService.Ip, insService.Port), opts...)
if err != nil {
2024-01-25 09:04:41 +00:00
log.Println(err)
continue
2024-01-19 08:23:47 +00:00
}
return New{{.ClientName}}Client(conn), nil
}
2023-11-27 09:36:02 +00:00
}
2024-01-25 09:04:41 +00:00
return nil, fmt.Errorf("no healthy with times 3")
2023-11-27 09:36:02 +00:00
}
{{end}}