Created
July 3, 2013 13:57
-
-
Save ptaoussanis/5918052 to your computer and use it in GitHub Desktop.
For Jan
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;; First we'll define a new kind of (degenerate) connection pool to encapsulate the behavior you want: | |
(defrecord SingletonPool [conn] ; Keeps a single connection atom | |
IConnectionPool | |
(get-conn [_ spec] | |
(or (when-let [c @conn] (when (conn-alive? c) c)) ; Aliveness check may not be necessary | |
(println "making a new conn!") | |
(reset! conn (make-new-connection spec)))) | |
(release-conn [_ _] nil) | |
(release-conn [this _ _] nil) | |
java.io.Closeable | |
(close [this] (when-let [c @conn] (reset! conn (close-conn c))))) | |
;;; And a helper: | |
(defmacro with-singleton-pool | |
[conn-name spec & body] | |
`(with-open [singleton-pool# (->SingletonPool (atom nil))] | |
(let [~conn-name {:pool singleton-pool# :spec ~spec}] | |
~@body))) | |
;;; Now we can code to [almost] the same API as if we had a real pool: | |
(with-singleton-pool c1 {} | |
(let [reply1 (wcar c1 (echo "foo")) | |
reply2 (wcar c1 (echo "bar"))] | |
(wcar c1 (set "my-key" (str reply1 reply2))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment