Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to store a global connection in Clojure?

Tags:

clojure

I have the following file that acts as the access point to my DB from my API endpoints. What is the proper way to maintain a single connection (or a connection pool?) for the life of the server?

(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
      )))
like image 321
bloudermilk Avatar asked Jul 20 '12 00:07

bloudermilk


2 Answers

the DATABASE_URL is stored, if you use with-connection macro for single connection. you can use c3p0 library for connection pool:

(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}))
like image 110
number23_cn Avatar answered Sep 25 '22 07:09

number23_cn


I also recommend c3p0. Clojure connection pooling provides a succinct introduction to how to configure clojure.java.jdbc with c3p0.

like image 22
tnoda Avatar answered Sep 22 '22 07:09

tnoda