79 lines
1.7 KiB
Go
79 lines
1.7 KiB
Go
package grpc_client
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/credentials/insecure"
|
|
"google.golang.org/grpc/status"
|
|
)
|
|
|
|
type ClientFactory struct {
|
|
connections map[string]*grpc.ClientConn
|
|
}
|
|
|
|
func NewClientFactory() *ClientFactory {
|
|
return &ClientFactory{
|
|
connections: make(map[string]*grpc.ClientConn),
|
|
}
|
|
}
|
|
|
|
const (
|
|
maxRetries = 3
|
|
retryDelay = 500 * time.Millisecond
|
|
)
|
|
|
|
func (f *ClientFactory) GetConnection(ctx context.Context, address string) (*grpc.ClientConn, error) {
|
|
if conn, ok := f.connections[address]; ok {
|
|
return conn, nil
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
|
defer cancel()
|
|
|
|
conn, err := grpc.DialContext(ctx, address,
|
|
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
|
grpc.WithBlock(),
|
|
)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to connect to %s: %w", address, err)
|
|
}
|
|
|
|
f.connections[address] = conn
|
|
return conn, nil
|
|
}
|
|
|
|
func (f *ClientFactory) GetConnectionWithRetry(ctx context.Context, address string) (*grpc.ClientConn, error) {
|
|
var conn *grpc.ClientConn
|
|
var err error
|
|
|
|
for i := 0; i < maxRetries; i++ {
|
|
conn, err = f.GetConnection(ctx, address)
|
|
if err == nil {
|
|
return conn, nil
|
|
}
|
|
|
|
st, ok := status.FromError(err)
|
|
if ok && (st.Code() == codes.Unavailable || st.Code() == codes.ResourceExhausted) {
|
|
time.Sleep(retryDelay)
|
|
continue
|
|
}
|
|
|
|
break
|
|
}
|
|
|
|
return nil, fmt.Errorf("failed to connect to %s after %d retries: %w", address, maxRetries, err)
|
|
}
|
|
|
|
func (f *ClientFactory) Close() error {
|
|
for addr, conn := range f.connections {
|
|
if err := conn.Close(); err != nil {
|
|
return fmt.Errorf("failed to close connection to %s: %w", addr, err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|