/
core.clj
254 lines (214 loc) · 8.34 KB
/
core.clj
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
;; Copyright (c) 2011-2014 Michael S. Klishin
;;
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns langohr.core
"Functions that work with connections and shared features between connections
and channels (e.g. shutdown listeners).
Relevant guides:
* http://clojurerabbitmq.info/articles/connecting.html
* http://clojurerabbitmq.info/articles/tls.html"
(:import [com.rabbitmq.client Connection Channel Address ConnectionFactory ShutdownListener BlockedListener]
[com.novemberain.langohr Recoverable]
[clojure.lang IFn]
[com.rabbitmq.client.impl AMQConnection])
(:require langohr.channel
[clojure.string :as s]
[clojure.walk :as walk]))
;;
;; Implementation
;;
(def ^{:dynamic true :doc "Default connection settings."} *default-config*
{:username "guest"
:password "guest"
:vhost "/"
:host "localhost"
:port ConnectionFactory/DEFAULT_AMQP_PORT})
;;
;; API
;;
(defprotocol Closeable
(close [c] "Closes given entity"))
(extend-protocol Closeable
com.rabbitmq.client.Connection
(close [this] (.close this))
com.rabbitmq.client.Channel
(close [this] (.close this)))
(defprotocol Openable
(open? [this] "Checks whether given entity is open")
(closed? [this] "Checks whether given entity is closed"))
(extend-protocol Openable
com.rabbitmq.client.Connection
(open? [conn] (.isOpen conn))
(closed? [conn] (not (.isOpen conn)))
com.rabbitmq.client.Channel
(open? [ch] (.isOpen ch))
(closed? [ch] (not (.isOpen ch))))
(def ^{:const true}
version "2.11.0-SNAPSHOT")
(declare create-connection-factory normalize-settings)
(defn- address-array-from
[addresses port]
(into-array Address
(map (fn [arg]
(let [[host port] (if (coll? arg)
[(first arg) (second arg)]
[arg port])]
(Address. host port)))
(remove nil? addresses))))
(defn ^Connection connect
"Creates and returns a new connection to RabbitMQ."
;; defaults
([]
(let [^ConnectionFactory cf (create-connection-factory {})]
(doto (com.novemberain.langohr.Connection. cf)
.init)))
;; settings
([settings]
(let [settings' (normalize-settings settings)
^ConnectionFactory cf (create-connection-factory settings')
xs (address-array-from (get settings' :hosts #{})
(get settings' :port ConnectionFactory/DEFAULT_AMQP_PORT))]
(doto (com.novemberain.langohr.Connection. cf (dissoc settings :password :username))
(.init xs)))))
(defn ^Channel create-channel
"Delegates to langohr.channel/open, kept for backwards compatibility"
[& args]
(apply langohr.channel/open args))
(defn ^ShutdownListener shutdown-listener
"Adds new shutdown signal listener that delegates to given function"
[^clojure.lang.IFn f]
(reify ShutdownListener
(shutdownCompleted [this cause]
(f cause))))
(defn ^ShutdownListener add-shutdown-listener
"Adds a shutdown listener on connection and returns it"
[^Connection c ^IFn f]
(let [lnr (shutdown-listener f)]
(.addShutdownListener c lnr)
lnr))
(defn ^BlockedListener blocked-listener
"Reifies connection.blocked and connection.unblocked listener from Clojure
functions"
[^IFn on-blocked ^IFn on-unblocked]
(reify BlockedListener
(^void handleBlocked [this ^String reason]
(on-blocked reason))
(^void handleUnblocked [this]
(on-unblocked))))
(defn ^BlockedListener add-blocked-listener
"Adds a connection.blocked and connection.unblocked listener
on connection and returns it"
[^Connection c ^IFn on-blocked ^IFn on-unblocked]
(let [lnr (blocked-listener on-blocked on-unblocked)]
(.addBlockedListener c lnr)
lnr))
(defn settings-from
"Parses AMQP connection URI and returns a persistent map of settings"
[^String uri]
(if uri
(let [cf (doto (ConnectionFactory.)
(.setUri uri))]
{:host (.getHost cf)
:port (.getPort cf)
:vhost (.getVirtualHost cf)
:username (.getUsername cf)
:password (.getPassword cf)})
*default-config*))
(defn capabilities-of
"Returns capabilities of the broker on the other side of the connection"
[^Connection conn]
(walk/keywordize-keys (into {} (-> conn .getServerProperties (get "capabilities")))))
;;
;; Recovery
;;
(defn automatic-recovery-enabled?
"Returns true if provided connection uses automatic connection recovery
mode, false otherwise"
[^com.novemberain.langohr.Connection conn]
(.automaticRecoveryEnabled conn))
(defn ^{:deprecated true} automatically-recover?
"See automatic-recovery-enabled?"
[^com.novemberain.langohr.Connection c]
(automatic-recovery-enabled? c))
(defn automatic-topology-recovery-enabled?
"Returns true if provided connection uses automatic topology recovery
mode, false otherwise"
[^com.novemberain.langohr.Connection conn]
(.automaticTopologyRecoveryEnabled conn))
(defn on-recovery
"Registers a network recovery callback on a (Langohr) connection or channel"
[^Recoverable target ^IFn callback]
(.onRecovery target callback))
;;
;; Advanced Customization
;;
(defn thread-factory-from
"Instantiates a java.util.concurrent.ThreadFactory that delegates
#newThread to provided Clojure function"
[f]
(reify java.util.concurrent.ThreadFactory
(^Thread newThread [this ^Runnable r]
(f r))))
;;
;; Implementation
;;
(defn normalize-settings
"For setting maps that contain keys such as :host, :username, :vhost, returns the argument"
[config]
(let [{:keys [host hosts]} config
hosts' (into #{} (remove nil? (or hosts #{host})))]
(merge (settings-from (:uri config (System/getenv "RABBITMQ_URL")))
{:hosts hosts'}
config)))
(defn- platform-string
[]
(let []
(format "Clojure %s on %s %s"
(clojure-version)
(System/getProperty "java.vm.name")
(System/getProperty "java.version"))))
(def ^{:private true}
client-properties {"product" "Langohr"
"information" "See http://clojurerabbitmq.info/"
"platform" (platform-string)
"capabilities" (get (AMQConnection/defaultClientProperties) "capabilities")
"copyright" "Copyright (C) 2011-2014 Michael S. Klishin, Alex Petrov"
"version" version})
(defn- ^ConnectionFactory create-connection-factory
"Creates connection factory from given attributes"
[settings]
(let [{:keys [host port username password vhost
requested-heartbeat connection-timeout ssl ssl-context socket-factory sasl-config
requested-channel-max thread-factory]
:or {requested-heartbeat ConnectionFactory/DEFAULT_HEARTBEAT
connection-timeout ConnectionFactory/DEFAULT_CONNECTION_TIMEOUT
requested-channel-max ConnectionFactory/DEFAULT_CHANNEL_MAX}} (normalize-settings settings)
cf (ConnectionFactory.)
final-port (if (and ssl (= port ConnectionFactory/DEFAULT_AMQP_PORT))
ConnectionFactory/DEFAULT_AMQP_OVER_SSL_PORT
port)]
(when (or ssl
(= port ConnectionFactory/DEFAULT_AMQP_OVER_SSL_PORT))
(.useSslProtocol cf))
(doto cf
(.setClientProperties client-properties)
(.setUsername username)
(.setPassword password)
(.setVirtualHost vhost)
(.setHost host)
(.setPort final-port)
(.setRequestedHeartbeat requested-heartbeat)
(.setConnectionTimeout connection-timeout)
(.setRequestedChannelMax requested-channel-max))
(when sasl-config
(.setSaslConfig cf sasl-config))
(when ssl-context
(.useSslProtocol cf ^javax.net.ssl.SSLContext ssl-context))
(when thread-factory
(.setThreadFactory cf ^ThreadFactory thread-factory))
cf))