🚑 Fix query services too much 429

This commit is contained in:
2024-06-23 16:11:49 +08:00
parent b919e100e0
commit 7ddbea8bcb
2 changed files with 26 additions and 6 deletions

View File

@ -1,15 +1,20 @@
package hyper
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
health "google.golang.org/grpc/health/grpc_health_v1"
"time"
_ "github.com/mbobakov/grpc-consul-resolver"
)
type HyperConn struct {
Addr string
cacheGrpcConn map[string]*grpc.ClientConn
}
func NewHyperConn(addr string) *HyperConn {
@ -17,10 +22,26 @@ func NewHyperConn(addr string) *HyperConn {
}
func (v *HyperConn) DiscoverServiceGRPC(name string) (*grpc.ClientConn, error) {
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)
}
}
target := fmt.Sprintf("consul://%s/%s", v.Addr, name)
return grpc.NewClient(
conn, err := grpc.NewClient(
target,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
)
if err == nil {
v.cacheGrpcConn[name] = conn
}
return conn, err
}