-
Notifications
You must be signed in to change notification settings - Fork 0
/
mq.go
76 lines (66 loc) · 1.26 KB
/
mq.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
package scheduler
import (
"fmt"
"github.com/streadway/amqp"
)
type Mq interface {
Connect() error
Close()
Send(string) error
}
type MqImpl struct {
Config *Conf
name string
Conn *amqp.Connection
Ch *amqp.Channel
Q *amqp.Queue
}
func NewMq(config *Conf, name string) *Mq {
var mq Mq
mq = &MqImpl{Config: config, name: name}
return &mq
}
func (m *MqImpl) Connect() error {
url := fmt.Sprintf("amqp://%s:%s@%s:%s/", m.Config.MSG.User, m.Config.MSG.Password, m.Config.MSG.Host, m.Config.MSG.Port)
conn, err := amqp.Dial(url)
if err != nil {
return err
} else {
m.Conn = conn
ch, err := m.Conn.Channel()
if err != nil {
return err
} else {
m.Ch = ch
q, err := m.Ch.QueueDeclare(
m.name, // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err == nil {
m.Q = &q
return nil
} else {
return err
}
}
}
}
func (m *MqImpl) Close() {
_ = m.Ch.Close()
_ = m.Conn.Close()
}
func (m *MqImpl) Send(msg string) error {
return m.Ch.Publish(
"", // exchange
m.Q.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
Body: []byte(msg),
})
}