-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrabbitmq.go
211 lines (178 loc) · 4.23 KB
/
rabbitmq.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package main
import (
"errors"
"github.com/streadway/amqp"
"log"
"os"
"time"
)
type Session struct {
name string
logger *log.Logger
connection *amqp.Connection
channel *amqp.Channel
done chan bool
notifyConnClose chan *amqp.Error
notifyChanClose chan *amqp.Error
notifyConfirm chan amqp.Confirmation
isReady bool
}
const (
// When reconnecting to the server after connection failure
reconnectDelay = 5 * time.Second
// When setting up the channel after a channel exception
reInitDelay = 2 * time.Second
// When resending messages the server didn't confirm
resendDelay = 5 * time.Second
)
var (
errNotConnected = errors.New("not connected to a server")
errAlreadyClosed = errors.New("already closed: not connected to the server")
errShutdown = errors.New("session is shutting down")
)
func New(name string, addr string) *Session {
session := Session{
logger: log.New(os.Stdout, "", log.LstdFlags),
name: name,
done: make(chan bool),
}
go session.handleReconnect(addr)
return &session
}
func (session *Session) handleReconnect(addr string) {
for {
session.isReady = false
log.Println("Attempting to connect")
conn, err := session.connect(addr)
if err != nil {
log.Println("Failed to connect. Retrying...")
select {
case <-session.done:
return
case <-time.After(reconnectDelay):
}
continue
}
if done := session.handleReInit(conn); done {
break
}
}
}
func (session *Session) connect(addr string) (*amqp.Connection, error) {
conn, err := amqp.Dial(addr)
if err != nil {
return nil, err
}
session.changeConnection(conn)
log.Println("Connected!")
return conn, nil
}
func (session *Session) handleReInit(conn *amqp.Connection) bool {
for {
session.isReady = false
err := session.init(conn)
if err != nil {
log.Println("Failed to initialize channel. Retrying...")
select {
case <-session.done:
return true
case <-time.After(reInitDelay):
}
continue
}
select {
case <-session.done:
return true
case <-session.notifyConnClose:
log.Println("Connection closed. Reconnecting...")
return false
case <-session.notifyChanClose:
log.Println("Channel closed. Re-running init...")
}
}
}
func (session *Session) init(conn *amqp.Connection) error {
ch, err := conn.Channel()
if err != nil {
return err
}
err = ch.Confirm(false)
if err != nil {
return err
}
session.changeChannel(ch)
session.isReady = true
log.Println("Setup!")
return nil
}
func (session *Session) changeConnection(connection *amqp.Connection) {
session.connection = connection
session.notifyConnClose = make(chan *amqp.Error)
session.connection.NotifyClose(session.notifyConnClose)
}
func (session *Session) changeChannel(channel *amqp.Channel) {
session.channel = channel
session.notifyChanClose = make(chan *amqp.Error)
session.notifyConfirm = make(chan amqp.Confirmation, 1)
session.channel.NotifyClose(session.notifyChanClose)
session.channel.NotifyPublish(session.notifyConfirm)
}
func (session *Session) Push(data []byte) error {
if !session.isReady {
return errors.New("failed to push: not connected")
}
for {
err := session.UnsafePush(data)
if err != nil {
session.logger.Println("Push failed. Retrying...")
select {
case <-session.done:
return errShutdown
case <-time.After(resendDelay):
}
continue
}
select {
case confirm := <-session.notifyConfirm:
if confirm.Ack {
return nil
} else {
}
case <-time.After(resendDelay):
}
}
}
func (session *Session) UnsafePush(data []byte) error {
if !session.isReady {
return errNotConnected
}
err := session.channel.Publish(
session.name, // Exchange
"", // Routing key
true, // Mandatory
false, // Immediate
amqp.Publishing{
ContentType: "application/json",
Body: data,
//DeliveryMode: amqp.Transient, // 1=non-persistent, 2=persistent
//Priority: 0,
},
)
return err
}
func (session *Session) Close() error {
if !session.isReady {
return errAlreadyClosed
}
err := session.channel.Close()
if err != nil {
return err
}
err = session.connection.Close()
if err != nil {
return err
}
close(session.done)
session.isReady = false
return nil
}