-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
52 lines (40 loc) · 931 Bytes
/
handler.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
package autonats
import (
"context"
"github.com/nats-io/nats.go"
)
type Handler interface {
Run(ctx context.Context) error // Subscribes to the queue and dispatches handler go-routines
Shutdown() // Shuts down all handlers gracefully
}
type Runner struct {
sub *nats.Subscription
}
func (r *Runner) Shutdown() error {
return r.sub.Unsubscribe()
}
func StartRunner(ctx context.Context, nc *nats.Conn, subj, group string, concurrency int, handleFn func(msg *nats.Msg)) (*Runner, error) {
subChan := make(chan *nats.Msg)
sub, err := nc.ChanQueueSubscribe(subj, group, subChan)
if err != nil {
return nil, err
}
for i := 0; i < concurrency; i++ {
go func() {
var msg *nats.Msg
var ok bool
for {
select {
case <-ctx.Done():
return
case msg, ok = <-subChan:
if !ok {
return
}
handleFn(msg)
}
}
}()
}
return &Runner{sub: sub}, nil
}