This repository has been archived by the owner on Nov 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
commandProcessor.go
83 lines (69 loc) · 1.97 KB
/
commandProcessor.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
package franklin
import (
"encoding/json"
"errors"
"log"
"reflect"
"github.com/streadway/amqp"
)
// CommandProcessor is a very early stage go port of the C# CommandProcessor,
// currently only posting messages over AMQ is supported.
type CommandProcessor interface {
Post(message Message) error
Close()
}
type amqpCommandProcessor struct {
subscriberRegistry *SubscriberRegistry
connection *amqp.Connection
channel *amqp.Channel
exchange string
}
func (cp *amqpCommandProcessor) Post(message Message) error {
body, err := json.Marshal(message)
if err != nil {
log.Print(err.Error())
return errors.New("Failed to marshal message")
}
routingKey := cp.subscriberRegistry.KeyForMessage(message)
err = cp.channel.Publish(
cp.exchange, // exchange
routingKey, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
Body: []byte(body)})
if err != nil {
log.Print(err.Error())
return errors.New("Failed to publish message")
}
log.Printf("Sent %s %s to %s", reflect.TypeOf(message), body, routingKey)
return nil
}
func (cp *amqpCommandProcessor) Close() {
cp.channel.Close()
cp.connection.Close()
}
// InitialiseCommandProcessor initialises an amqpCommandProcessor and
// establishes an AMQ connection.
func InitialiseCommandProcessor(url string, exchange string, subscriberRegistry *SubscriberRegistry) CommandProcessor {
conn, err := amqp.Dial(url)
failOnError(err, "Failed to connect to RabbitMQ")
ch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
err = ch.ExchangeDeclare(
exchange, // name
"direct", // type
true, // durable
false, // auto-deleted
false, // internal
false, // no-wait
nil, // arguments
)
failOnError(err, "Failed to declare exchange")
return &amqpCommandProcessor{
subscriberRegistry: subscriberRegistry,
connection: conn,
channel: ch,
exchange: exchange}
}