-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpool_example.go
134 lines (120 loc) · 2.33 KB
/
pool_example.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package main
import (
"./pool"
"bufio"
"errors"
"fmt"
"math/rand"
"net"
"strconv"
"sync"
"time"
)
var fmt_print_lock = sync.RWMutex{}
func printRed(v interface{}) {
fmt_print_lock.Lock()
defer fmt_print_lock.Unlock()
fmt.Printf("\033[41;37;5m%v\033[0m", v)
}
func printGreen(v interface{}) {
fmt_print_lock.Lock()
defer fmt_print_lock.Unlock()
fmt.Printf("\033[42;37;5m%v\033[0m", v)
}
func printYellow(v interface{}) {
fmt_print_lock.Lock()
defer fmt_print_lock.Unlock()
fmt.Printf("\033[43;37;5m%v\033[0m", v)
}
func printBlue(v interface{}) {
fmt_print_lock.Lock()
defer fmt_print_lock.Unlock()
fmt.Printf("\033[44;37;5m%v\033[0m", v)
}
func tcp_testserver() {
ln, err := net.Listen("tcp", "0.0.0.0:8888")
if err != nil {
fmt.Println("server error", err)
// handle error
} else {
}
for {
conn, err := ln.Accept()
if err != nil {
printRed(0)
} else {
reader := bufio.NewReader(conn)
writer := bufio.NewWriter(conn)
go func() {
for {
_, _, err := reader.ReadLine()
if err != nil {
printRed(1)
printRed(err)
break
}
//fmt.Println("server got:", string(buf))
//time.Sleep(50000 * time.Second)
writer.WriteString("PONG\r\n")
writer.Flush()
}
}()
}
}
}
func newPool() *pool.Pool {
return &pool.Pool{
MaxActive: 100,
IdleTimeout: 1 * time.Minute,
Dial: func() (pool.Conn, error) {
printBlue(0)
return pool.DialTimeout("tcp", "0.0.0.0:8888", 5*time.Second, 5*time.Second, 5*time.Second)
},
TestOnBorrow: nil,
Wait: true,
}
}
func client_ping(pool *pool.Pool, s string) {
n := 0
for {
if n > 1 {
//return
}
if c, err := pool.Get(); err == nil {
printGreen(0)
err := c.WriteStringLine(s)
if rand.Intn(10) == 5 {
err = errors.New("fake error")
}
if c.Fatal(err) != nil {
printRed(3)
printRed(err)
} else {
_, err = c.ReadBytesLine()
if c.Fatal(err) != nil {
printRed(4)
printRed(err)
} else {
printYellow(0)
}
}
c.Close()
} else {
printRed(2)
printRed(err)
}
n++
time.Sleep(time.Duration(rand.Intn(10)+1) * time.Second)
}
}
func main() {
done := make(chan bool)
go tcp_testserver()
time.Sleep(1 * time.Second)
p := newPool()
for i := 0; i < 100000; i++ {
go client_ping(p, "ping"+strconv.Itoa(i))
//client_ping(p, "PING2")
}
<-done
}