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
)))
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}))
I also recommend c3p0.
Clojure connection pooling
provides a succinct introduction to how to configure clojure.java.jdbc
with c3p0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With