2012-07-20 60 views
5

我有以下文件充當從我的API端點到我的數據庫的訪問點。在服務器的整個生命週期中維護單個連接(或連接池?)的正確方法是什麼?在Clojure中存儲全局連接的正確方法是什麼?

(ns my-api.repository 
    (:require [clojure.java.jdbc :as sql])) 

(defn some-query 
    (sql/with-connection (System/getenv "DATABASE_URL") 
    (sql/with-query-results results 
     ;; You get the picture 
    ))) 

回答

4

DATABASE_URL存儲,如果你使用with-connection宏單個連接。你可以使用連接池的c3p0庫:

(defn pooled-spec 
    "return pooled conn spec. 
    Usage: 
    (def pooled-db (pooled-spec db-spec)) 
    (with-connection pooled-db ...)" 
    [{:keys [classname subprotocol subname user password] :as other-spec}] 
    (let [cpds (doto (ComboPooledDataSource.) 
       (.setDriverClass classname) 
       (.setJdbcUrl (str "jdbc:" subprotocol ":" subname)) 
       (.setUser user) 
       (.setPassword password))] 
    {:datasource cpds})) 
0

我不認爲與連接持有任何開放。 Doc或者Source都提出了這個問題,在2.3中,我可以在運行查詢後通過檢查db來確認它。源代碼看起來像這樣:

(defn with-connection* 
    "Evaluates func in the context of a new connection to a database then 
    closes the connection." 
    [db-spec func] 
    (with-open [^java.sql.Connection con (get-connection db-spec)] 
    (binding [*db* (assoc *db* :connection con :level 0 :rollback (atom false))] 
     (func)))) 

連接池可能在延遲創建它們時很有用,但這並不會使它們保持打開狀態。使連接可設置似乎是必要的。然而,最新的API強調創建連接並將其傳遞給每個呼叫。雖然仍然是ALPHA,但這看起來像是這個庫的未來(並且仍然與連接池兼容)。從圖書館的維基:

(require '[clojure.java.jdbc :as j] 
    '[clojure.java.jdbc.sql :as s]) 

(def mysql-db {:subprotocol "mysql" 
       :subname "//127.0.0.1:3306/clojure_test" 
       :user "clojure_test" 
       :password "clojure_test"}) 

(j/insert! mysql-db :fruit 
    {:name "Apple" :appearance "rosy" :cost 24} 
    {:name "Orange" :appearance "round" :cost 49}) 
1

jdbc-pool簡化了使用C3P0與clojure.java.jdbc的過程。爲了這個目的,我專門創建了這個庫(也是唯一的)。

相關問題