Clojure: the best approach for single point data connection

I am creating a connection to elasticsearch (but replacing any other data source to your liking here) and it will be based on the environment or configuration file at runtime. It looks like this:

(defn create-conn
  "Connect to the given uri. This is a persistent conn managed by clj-http (apache)."
  ([uri]
   ( ;;; create a persistent connection using clj-http / elastic
   ...)
  ([]
   (create-conn (or (System/getenv "ES_URL")
                    (cfg/get-url-from-config-file)
                    "http://localhost:9200"))))

Since the connection will not change during the entire life of the server, I will only need to run this function once and cache the result. There are several ways to do this:

1 - memoizeit - while this works, this does not seem to be the right approach, since I only cached one thing

2 - use a state manager, for example Component or mount; since I really do not control the state, I just set and forget, and only using it for this, does he feel a little overdone. For example, what does the following look like higher than # 3?

; mount version -- good, but how is this better than #3 below?
(defstate conn :start (getconn))
(mount/start #'elastic/conn)   ;; somewhere else, must start mount

3 - defit. Despite the fact that the launch create-conndoes not actually perform any network activity, I would prefer not to run it when the file is uploaded, which would happen if I just did the usual one defon it, so I would have to do something like the following .. Please note that the function getconnis for convenience, so I should not directly deref conn:

(def conn (delay (create-conn)))
(defn getconn [] @conn)

4 - use atom- directly, but this is not a var to be changed, and it enters a state where it is not needed:

(def conn (atom nil))
(def getconn []
  (if-not @conn (reset! conn (create-conn)))
  @conn)

5 - [insert your idea here]

3, , delay . , ?

+4
2

Mount component - , ( ). Mount - "" , .

+2

conn , , , , . , REPL , . , . , , - def ( ). - , .

0
source

Source: https://habr.com/ru/post/1655109/


All Articles