/
request.go
133 lines (113 loc) · 2.49 KB
/
request.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package nano
import (
"errors"
"fmt"
log "github.com/Sirupsen/logrus"
"github.com/streadway/amqp"
"github.com/streamrail/concurrent-map"
"strconv"
"sync/atomic"
"time"
)
type rpcQueue struct {
name string
channels cmap.ConcurrentMap
amqpChannel *amqp.Channel
correlationId uint64
}
var li int
func (q *rpcQueue) Request(routingKey string, contentType string, body []byte) (string, []byte, error) {
corrId := strconv.FormatUint(atomic.AddUint64(&(q.correlationId), 2), 10)
resChan := make(chan *amqp.Delivery)
_, exists := q.channels.Get(corrId)
if exists {
log.Error("Correlation id already exists")
return "", nil, errors.New("Correlation id already exists")
}
q.channels.Set(corrId, resChan)
fmt.Printf("Send request to %s\n", routingKey)
err := q.amqpChannel.Publish(
"", // exchange
routingKey, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: contentType,
CorrelationId: corrId,
ReplyTo: q.name,
Body: body,
})
if err != nil {
return "", nil, err
}
d := <-resChan
return d.ContentType, d.Body, nil
}
func newRPCQueue(uri string) (*rpcQueue, error) {
fmt.Println("newRPCQueue")
var conn *amqp.Connection
var err error
for try := 0; try < 10; try++ {
log.Infof("Attempt to connect to RabbitMQ: %d", try+1)
conn, err = amqp.Dial(uri)
if err == nil {
break
}
time.Sleep(time.Second * 5)
}
if err != nil {
return nil, err
}
amqpChannel, err := conn.Channel()
if err != nil {
conn.Close()
return nil, err
}
queue, err := amqpChannel.QueueDeclare(
"", // name
false, // durable
false, // delete when usused
true, // exclusive
false, // noWait
nil, // arguments
)
if err != nil {
amqpChannel.Close()
conn.Close()
return nil, err
}
name := queue.Name
msgs, err := amqpChannel.Consume(
name, // queue
"", // consumer
true, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
if err != nil {
amqpChannel.Close()
conn.Close()
return nil, err
}
q := rpcQueue{
name: name,
channels: cmap.New(),
amqpChannel: amqpChannel,
correlationId: 0,
}
go func() {
for d := range msgs {
corrId := d.CorrelationId
context, exists := q.channels.Get(corrId)
if exists {
q.channels.Remove(corrId)
context.(chan *amqp.Delivery) <- &d
} else {
log.Errorf("Cannot handle RPC request (correlation id = %s)", corrId)
}
}
}()
return &q, nil
}