This repository has been archived by the owner on Oct 8, 2022. It is now read-only.
/
queue.go
91 lines (69 loc) · 2.59 KB
/
queue.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package webqueue
import (
"fmt"
"github.com/streadway/amqp"
"time"
)
func StartLine(rabbitConf RabbitMQConfig, lineConf LineConfig) {
consumerConn := createRabbitMqConnection(rabbitConf)
publisherConn := createRabbitMqConnection(rabbitConf)
defer consumerConn.Close()
defer publisherConn.Close()
consumerChannel, err := consumerConn.Channel()
panicOnError(err, "Could not create consumer channel")
defer consumerChannel.Close()
producerChannel, err := publisherConn.Channel()
panicOnError(err, "Could not create producer channel")
defer consumerChannel.Close()
defer producerChannel.Close()
// Create the exchange we (re)publish to
createRabbitMqExchange(producerChannel, lineConf)
q, err := consumerChannel.QueueDeclare(lineConf.Queue, false, false, false, false, nil)
panicOnError(err, "Could not create queue")
err = consumerChannel.QueueBind(lineConf.Queue, "#", lineConf.Queue, false, nil)
panicOnError(err, "Could not bind exchange to queue")
consumerChannel.Qos(lineConf.MaxConcurrent, 0, false)
consumer, err := consumerChannel.Consume(q.Name, "", false, false, false, false, nil)
panicOnError(err, "Could not create consumer")
forever := make(chan bool)
processor := Processor{}
processor.Init(lineConf)
go func() {
for d := range consumer {
Log.Info("Received message: %s", d.Body)
success := processor.HandleMessage(string(d.Body))
if success {
d.Ack(false)
continue
}
d.Ack(false)
producerChannel.Publish(lineConf.Queue, "", false, false, amqp.Publishing{
DeliveryMode: d.DeliveryMode,
Timestamp: time.Now(),
Body: d.Body,
})
}
}()
Log.Notice("Waiting for messages. Press CTRL+C to exit...")
<-forever
}
func createRabbitMqConnection(rabbitConf RabbitMQConfig) *amqp.Connection {
publisherConn, err := amqp.Dial(fmt.Sprintf("amqp://%s:%d/", rabbitConf.Host, rabbitConf.Port))
panicOnError(err, "Could not connect to RabbitMQ")
return publisherConn
}
func createRabbitMqExchange(channel *amqp.Channel, lineConf LineConfig) {
err := channel.ExchangeDeclare(lineConf.Queue, "topic", true, false, false, false, nil)
panicOnError(err, "Could not create exchange")
}
func PublishToLine(payload string, lineConf LineConfig, rabbitConf RabbitMQConfig) error {
conn := createRabbitMqConnection(rabbitConf)
producerChannel, err := conn.Channel()
panicOnError(err, "Could not create new RabbitMQ channel")
createRabbitMqExchange(producerChannel, lineConf)
return producerChannel.Publish(lineConf.Queue, "", false, false, amqp.Publishing{
DeliveryMode: amqp.Transient,
Timestamp: time.Now(),
Body: []byte(payload),
})
}