-
Notifications
You must be signed in to change notification settings - Fork 2
/
pool_test.go
95 lines (87 loc) · 2.26 KB
/
pool_test.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 grpcpool
import (
"context"
"log"
"net"
"net/http"
_ "net/http/pprof"
"runtime"
"sync"
"testing"
"time"
assertpkg "github.com/stretchr/testify/assert"
"google.golang.org/grpc"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
"google.golang.org/grpc/reflection"
)
const (
port = ":19800"
)
// server is used to implement helloworld.GreeterServer.
type server struct{}
// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}
func init() {
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
// start a gRPC hello world server
go func() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterGreeterServer(s, &server{})
// Register reflection service on gRPC server.
reflection.Register(s)
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}()
}
func TestGetAndBack(t *testing.T) {
wg := sync.WaitGroup{}
assert := assertpkg.New(t)
sa := ServiceArg{
Service: "hello",
Target: "127.0.0.1:19800",
Opts: []grpc.DialOption{grpc.WithInsecure()},
}
err := Create(context.Background(), grpc.Dial, runtime.NumCPU(), runtime.NumCPU()*2, sa)
if !assert.NoError(err, "gRPC.Create") {
t.Fatal(err)
}
connCount := runtime.NumCPU() * 20
wg.Add(connCount)
for i := 0; i < connCount; i++ {
go func(t *testing.T, wg *sync.WaitGroup) {
conn, err := Get(context.Background(), sa.Service)
if !assert.NoError(err, "gRPC.Get") {
t.Fatal(err)
}
client := pb.NewGreeterClient(conn)
r := &pb.HelloRequest{
Name: "client",
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
defer cancel()
res, err := client.SayHello(ctx, r)
if !assert.NoError(err, "SayHello") {
t.Fatal(err)
}
if !assert.EqualValues(res.Message, "Hello "+r.Name, "SayHello") {
t.Fatal()
}
PutBack(context.Background(), sa.Service, conn)
wg.Done()
}(t, &wg)
}
wg.Wait()
if !assert.EqualValues(runtime.NumCPU()*2, Len(context.Background(), sa.Service), "max idle connection") {
t.Failed()
}
Close(context.Background())
}