-
Notifications
You must be signed in to change notification settings - Fork 1
/
connection_pool.go
51 lines (42 loc) · 1.02 KB
/
connection_pool.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
package goload_grpc
import (
"log"
"math/rand"
"time"
"google.golang.org/grpc"
)
type ConnectionPool struct {
conns []*grpc.ClientConn
rand *rand.Rand
}
// Creates a new GRPC based connection pool for the given `target` and with the `opts` from GRPC.
//
// The connections are safe to be used from multiple goroutines.
func NewConnectionPool(
count int,
target string,
opts ...grpc.DialOption,
) *ConnectionPool {
conns := make([]*grpc.ClientConn, count)
for i := 0; i < count; i++ {
conn, err := grpc.Dial(target, opts...)
if err != nil {
log.Fatalf("Unable to dial GRPC connection: %v", err)
}
conns[i] = conn
}
return &ConnectionPool{
conns: conns,
rand: rand.New(rand.NewSource(time.Now().Unix())),
}
}
// Picks a random connection from the pool.
func (pool *ConnectionPool) Connection() *grpc.ClientConn {
return pool.conns[pool.rand.Intn(len(pool.conns))]
}
// Closes all of the connections in the pool
func (pool *ConnectionPool) Close() {
for _, conn := range pool.conns {
conn.Close()
}
}