-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpcclient.go
95 lines (81 loc) · 2.44 KB
/
rpcclient.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Package client provides a gRPC client for service discovery.
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: 2023 werbenhu
// SPDX-FileContributor: werbenhu
package client
import (
"context"
"time"
"github.com/werbenhu/registry"
"google.golang.org/grpc"
)
// RpcClient is a gRPC client for service discovery.
type RpcClient struct {
// Addr is the registry server address.
Addr string
// conn is the gRPC connection.
conn *grpc.ClientConn
// reg is the gRPC client object.
reg registry.RClient
}
// NewRpcClient creates a new RpcClient object and connects to the registry server at `addr`.
func NewRpcClient(addr string) (*RpcClient, error) {
client := &RpcClient{Addr: addr}
// Connect to the registry server.
conn, err := grpc.Dial(client.Addr, grpc.WithInsecure())
if err != nil {
return nil, err
}
client.conn = conn
client.reg = registry.NewRClient(conn)
return client, nil
}
// Close closes the gRPC client connection.
func (c *RpcClient) Close() {
c.conn.Close()
}
// Match assigns a service to a key using the consistent hashing algorithm.
//
// Parameters:
// - group: The group name of the services.
// - key: The key, such as user ID, device ID, etc.
//
// Returns:
// - The service that matches the key.
// - An error if the service cannot be found.
func (c *RpcClient) Match(group string, key string) (*registry.Service, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
service, err := c.reg.Match(ctx, ®istry.MatchRequest{
Group: group,
Key: key,
})
if err != nil {
return nil, err
}
// The service contains three attributes: service ID, group name, and service address.
return registry.NewService(service.Id, service.Group, service.Addr), nil
}
// Members returns the list of services in a group.
//
// Parameters:
// - group: The group name of the services.
//
// Returns:
// - The list of services in the group.
// - An error if the group does not exist or cannot be accessed.
func (c *RpcClient) Members(group string) ([]*registry.Service, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
services := make([]*registry.Service, 0)
members, err := c.reg.Members(ctx, ®istry.MembersRequest{
Group: group,
})
if err != nil {
return services, err
}
for _, member := range members.Services {
services = append(services, registry.NewService(member.Id, member.Group, member.Addr))
}
return services, nil
}