-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcpconnpool.go
More file actions
72 lines (63 loc) · 1.62 KB
/
tcpconnpool.go
File metadata and controls
72 lines (63 loc) · 1.62 KB
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
package TCPconnPool
import (
"errors"
"log"
"net"
"sync/atomic"
)
type ConnectionPool struct {
connections chan net.Conn
maxSize uint64
}
var TotalConnections uint64
func CreateConnectionPool(initialSize int, maximumSize uint64) (*ConnectionPool, error) {
log.Println("Connection pool is being created!")
pool := &ConnectionPool{
connections: make(chan net.Conn, maximumSize),
maxSize: maximumSize,
}
TotalConnections = 0
// Creating the number of initial connections
for iterator := 0; iterator < initialSize; iterator++ {
atomic.AddUint64(&TotalConnections, 1)
singleConnection, er := net.Dial("tcp", "localhost:8081")
if er != nil {
log.Fatal("error in creating initial connections: ", er.Error())
}
pool.connections <- singleConnection
}
return pool, nil
}
func (pool *ConnectionPool) GetOneConnection() (net.Conn, error) {
if atomic.LoadUint64(&TotalConnections) >= pool.maxSize {
singleConnection := <-pool.connections
return singleConnection, nil
} else {
select {
case singleConnection := <-pool.connections:
if singleConnection == nil {
return nil, errors.New("returned a nil connection.")
}
return singleConnection, nil
default:
atomic.AddUint64(&TotalConnections, 1)
return net.Dial("tcp", "localhost:8081")
}
}
}
func (pool *ConnectionPool) PutOneConnection(singleConnection net.Conn) error {
if singleConnection == nil {
return nil
}
if pool.connections == nil {
singleConnection.Close()
return errors.New("pool was already closed")
}
select {
case pool.connections <- singleConnection:
return nil
default:
singleConnection.Close()
return nil
}
}