-
-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathpolicy.go
More file actions
40 lines (31 loc) · 800 Bytes
/
policy.go
File metadata and controls
40 lines (31 loc) · 800 Bytes
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
package dbresolver
import (
"math/rand"
"sync/atomic"
"gorm.io/gorm"
)
type Policy interface {
Resolve([]gorm.ConnPool) gorm.ConnPool
}
type PolicyFunc func([]gorm.ConnPool) gorm.ConnPool
func (f PolicyFunc) Resolve(connPools []gorm.ConnPool) gorm.ConnPool {
return f(connPools)
}
type RandomPolicy struct {
}
func (RandomPolicy) Resolve(connPools []gorm.ConnPool) gorm.ConnPool {
return connPools[rand.Intn(len(connPools))]
}
func RoundRobinPolicy() Policy {
var i int
return PolicyFunc(func(connPools []gorm.ConnPool) gorm.ConnPool {
i = (i + 1) % len(connPools)
return connPools[i]
})
}
func StrictRoundRobinPolicy() Policy {
var i int64
return PolicyFunc(func(connPools []gorm.ConnPool) gorm.ConnPool {
return connPools[int(atomic.AddInt64(&i, 1))%len(connPools)]
})
}