2024-06-22 04:14:15 +00:00
|
|
|
package hyper
|
|
|
|
|
|
|
|
import (
|
2024-06-23 08:11:49 +00:00
|
|
|
"context"
|
2024-06-22 04:14:15 +00:00
|
|
|
"fmt"
|
|
|
|
"google.golang.org/grpc"
|
|
|
|
"google.golang.org/grpc/credentials/insecure"
|
2024-06-23 08:11:49 +00:00
|
|
|
health "google.golang.org/grpc/health/grpc_health_v1"
|
|
|
|
"time"
|
2024-06-22 12:05:21 +00:00
|
|
|
|
|
|
|
_ "github.com/mbobakov/grpc-consul-resolver"
|
2024-06-22 04:14:15 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type HyperConn struct {
|
|
|
|
Addr string
|
2024-06-23 08:11:49 +00:00
|
|
|
|
|
|
|
cacheGrpcConn map[string]*grpc.ClientConn
|
2024-06-22 04:14:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewHyperConn(addr string) *HyperConn {
|
|
|
|
return &HyperConn{Addr: addr}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (v *HyperConn) DiscoverServiceGRPC(name string) (*grpc.ClientConn, error) {
|
2024-06-23 08:11:49 +00:00
|
|
|
if val, ok := v.cacheGrpcConn[name]; ok {
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
|
|
|
|
defer cancel()
|
|
|
|
if _, err := health.NewHealthClient(val).Check(ctx, &health.HealthCheckRequest{
|
|
|
|
Service: name,
|
|
|
|
}); err == nil {
|
|
|
|
return val, nil
|
|
|
|
} else {
|
|
|
|
delete(v.cacheGrpcConn, name)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-06-22 04:14:15 +00:00
|
|
|
target := fmt.Sprintf("consul://%s/%s", v.Addr, name)
|
2024-06-23 08:11:49 +00:00
|
|
|
conn, err := grpc.NewClient(
|
2024-06-22 04:14:15 +00:00
|
|
|
target,
|
|
|
|
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
|
|
|
grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
|
|
|
|
)
|
2024-06-23 08:11:49 +00:00
|
|
|
if err == nil {
|
|
|
|
v.cacheGrpcConn[name] = conn
|
|
|
|
}
|
|
|
|
return conn, err
|
2024-06-22 04:14:15 +00:00
|
|
|
}
|