-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbasic.go
63 lines (51 loc) · 1.48 KB
/
basic.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
package main
import (
amqpRecipient "github.com/elegant-bro/amqp-recipient"
"github.com/elegant-bro/amqp-recipient/recipients"
amqp "github.com/rabbitmq/amqp091-go"
"log"
)
type Api struct{}
func (a *Api) Send( /*some args*/ ) error {
// some api call
return nil // or send error
}
type sendHandler struct {
api *Api
}
// Handle implementation of github.com/elegant-bro/amqp_recipient/JobHandler
func (s sendHandler) Handle(_ amqp.Delivery) (uint8, error) {
err := s.api.Send( /*convert delivery to args*/ )
if nil != err {
return amqpRecipient.HandlerReject, err
}
return amqpRecipient.HandlerAck, nil
}
func rabbitConnFromDsn(dsn string) *amqp.Connection {
conn, _ := amqp.Dial(dsn)
// don't ignore error in real project
return conn
}
func main() {
// first we create the recipient
r := recipients.NewDefaultAmqpRecipient(
"user.registered", // queue name
16, // prefetch count
rabbitConnFromDsn("rabbit dsn"),
&sendHandler{&Api{}},
func(d amqp.Delivery, err error) {
log.Printf("Message with id '%s' fails: %v", d.MessageId, err)
},
)
// then we subscribe it
job, err := r.Subscribe()
// Internally each subscription fetch channel from the connection and call channel.Consume() method
// you can call recipient.Subscribe as many times as consumers you need for the queue
if nil != err {
log.Fatalf("%s: %v", "can't subscribe to user.registered", err)
}
// the last we run the job as goroutine
go job.Run()
// prevent exit
<-make(chan bool)
}