forked from ti/mdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmdb.go
executable file
·83 lines (67 loc) · 1.88 KB
/
mdb.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
// The mdb package provides mongodb driver
// with automatic reconnection and retries when connection is break.
// It is wrapper over the mgo driver and exposes exactly the same API.
//
// mdb performs automatic retries under certain conditions.
// Mainly, if an error is returned by the client (connection errors).
// Otherwise, the error is returned.
package mdb
import (
"github.com/globalsign/mgo"
"time"
)
const (
DefaultMaxRetries = 2
DefaultRetryInterval = time.Second * 2
)
type Option func(session *Session)
func Dial(mgoUrl string, opts ...Option) (*Session, error) {
mgoSession, err := mgo.Dial(mgoUrl)
if err != nil {
return nil, err
}
sess := Wrap(mgoSession, DefaultMaxRetries, DefaultRetryInterval)
applyOptions(sess, opts...)
return sess, nil
}
func DialWithInfo(info *mgo.DialInfo, opts ...Option) (*Session, error) {
mgoSession, err := mgo.DialWithInfo(info)
if err != nil {
return nil, err
}
sess := Wrap(mgoSession, DefaultMaxRetries, DefaultRetryInterval)
applyOptions(sess, opts...)
return sess, nil
}
func DialWithTimeout(mgoUrl string, timeout time.Duration, opts ...Option) (*Session, error) {
mgoSession, err := mgo.DialWithTimeout(mgoUrl, timeout)
if err != nil {
return nil, err
}
sess := Wrap(mgoSession, DefaultMaxRetries, DefaultRetryInterval)
applyOptions(sess, opts...)
return sess, nil
}
func Wrap(sess *mgo.Session, maxRetries int, retryInterval time.Duration) *Session {
return &Session{
RetryInterval: retryInterval,
MaxConnectRetries: maxRetries,
originSession: sess,
refreshing: 0,
}
}
func MaxRetries(max int) func(session *Session) {
return func(s *Session) {
s.MaxConnectRetries = max
}
}
func RetryInterval(interval time.Duration) func(session *Session) {
return func(s *Session) {
s.RetryInterval = interval
}
}
func applyOptions(s *Session, opts ...Option) {
for _, o := range opts {
o(s)
}
}