forked from asynkron/protoactor-go
/
roundrobin_router.go
58 lines (45 loc) · 1.31 KB
/
roundrobin_router.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
package router
import (
"sync/atomic"
"github.com/AsynkronIT/protoactor-go/actor"
)
type roundRobinGroupRouter struct {
GroupRouter
}
type roundRobinPoolRouter struct {
PoolRouter
}
type roundRobinState struct {
index int32
routees *actor.PIDSet
values []actor.PID
}
func (state *roundRobinState) SetRoutees(routees *actor.PIDSet) {
state.routees = routees
state.values = routees.Values()
}
func (state *roundRobinState) GetRoutees() *actor.PIDSet {
return state.routees
}
func (state *roundRobinState) RouteMessage(message interface{}, sender *actor.PID) {
pid := roundRobinRoutee(&state.index, state.values)
pid.Request(message, sender)
}
func NewRoundRobinPool(size int) actor.Props {
return actor.FromSpawn(spawner(&roundRobinPoolRouter{PoolRouter{PoolSize: size}}))
}
func NewRoundRobinGroup(routees ...*actor.PID) actor.Props {
return actor.FromSpawn(spawner(&roundRobinGroupRouter{GroupRouter{Routees: actor.NewPIDSet(routees...)}}))
}
func (config *roundRobinPoolRouter) CreateRouterState() Interface {
return &roundRobinState{}
}
func (config *roundRobinGroupRouter) CreateRouterState() Interface {
return &roundRobinState{}
}
func roundRobinRoutee(index *int32, routees []actor.PID) actor.PID {
i := int(atomic.AddInt32(index, 1))
mod := len(routees)
routee := routees[i%mod]
return routee
}