This repository has been archived by the owner on Oct 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdriver_pool.go
110 lines (89 loc) · 2.55 KB
/
driver_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
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
package goBolt
import (
"context"
pool "github.com/jolestar/go-commons-pool"
"github.com/mindstand/go-bolt/bolt_mode"
"github.com/mindstand/go-bolt/connection"
"github.com/mindstand/go-bolt/errors"
"sync"
)
type driverPool struct {
connStr string
maxConns int
pool *pool.ObjectPool
refLock sync.Mutex
closed bool
}
func newDriverPool(connStr string, maxConns int) (*driverPool, error) {
dPool := pool.NewObjectPool(context.Background(), &ConnectionPooledObjectFactory{connectionString: connStr}, &pool.ObjectPoolConfig{
LIFO: true,
MaxTotal: maxConns,
MaxIdle: maxConns,
MinIdle: 5,
TestOnCreate: true,
TestOnBorrow: true,
TestOnReturn: true,
TestWhileIdle: true,
BlockWhenExhausted: true,
MinEvictableIdleTime: pool.DefaultMinEvictableIdleTime,
SoftMinEvictableIdleTime: pool.DefaultSoftMinEvictableIdleTime,
NumTestsPerEvictionRun: 3,
TimeBetweenEvictionRuns: 0,
})
return &driverPool{
connStr: connStr,
maxConns: maxConns,
pool: dPool,
}, nil
}
func (d *driverPool) open() (connection.IConnection, error) {
d.refLock.Lock()
defer d.refLock.Unlock()
if !d.closed {
connObj, err := d.pool.BorrowObject(context.Background())
if err != nil {
return nil, err
}
conn, ok := connObj.(connection.IConnection)
if !ok {
return nil, errors.Wrap(errors.ErrInternal, "cannot cast from [%T] to [IConnection]", connObj)
}
if !conn.ValidateOpen() {
return nil, errors.New("pool returned dead connection")
}
return conn, nil
}
return nil, errors.New("Driver pool has been closed")
}
func (d *driverPool) close() error {
d.refLock.Lock()
defer d.refLock.Unlock()
if d.closed {
return errors.Wrap(errors.ErrClosed, "internalDriver pool is already closed")
}
if d.pool == nil {
return errors.Wrap(errors.ErrPool, "connection pool is nil")
}
d.pool.Close(context.Background())
d.closed = true
return nil
}
func (d *driverPool) reclaim(conn connection.IConnection) error {
if conn == nil {
return errors.New("cannot reclaim nil connection")
}
return d.pool.ReturnObject(context.Background(), conn)
}
// ----------------------
type DriverPool struct {
internalPool *driverPool
}
func (d *DriverPool) Open(mode bolt_mode.AccessMode) (connection.IConnection, error) {
return d.internalPool.open()
}
func (d *DriverPool) Reclaim(conn connection.IConnection) error {
return d.internalPool.reclaim(conn)
}
func (d *DriverPool) Close() error {
return d.internalPool.close()
}