-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathendpoint.go
62 lines (51 loc) · 1.18 KB
/
endpoint.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
package grpcloadbalancing
import (
"time"
"google.golang.org/grpc"
)
// Endpoint represent endpoint struct
type Endpoint struct {
*grpc.ClientConn
url string
weight int
maxIddle int
lastUsed time.Time
generator func() (*grpc.ClientConn, error)
}
// NewEndpoint create endpoint together with client connection
func NewEndpoint(url string, weight, maxIddle int, generator func() (*grpc.ClientConn, error)) (*Endpoint, error) {
var err error
e := new(Endpoint)
e.url = url
e.weight = weight
e.maxIddle = maxIddle
e.lastUsed = time.Now()
e.ClientConn, err = generator()
if err != nil {
return nil, err
}
e.generator = generator
return e, nil
}
// GetClientConn get client connection of this endpoint
func (e *Endpoint) GetClientConn() *grpc.ClientConn {
return e.ClientConn
}
func (e *Endpoint) checkOrInitiateNewConnection() error {
if e.lastUsed.Add(time.Duration(e.maxIddle) * time.Second).Before(time.Now()) {
e.ClientConn.Close()
e.ClientConn = nil
}
var err error
if e.ClientConn == nil {
e.ClientConn, err = e.generator()
if err != nil {
return err
}
}
e.lastUsed = time.Now()
return nil
}
func (e *Endpoint) destroy() {
e.ClientConn.Close()
}