Last active
August 29, 2015 14:05
-
-
Save matstani/1d1fa5aec69c22dbd5e5 to your computer and use it in GitHub Desktop.
stuartsierra.component & ring & c3p0 pooled db connection.
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
(ns picture-gallery.component | |
(:require [com.stuartsierra.component :as component] | |
[picture-gallery.handler :refer [app]] | |
[ring.adapter.jetty :refer [run-jetty]]) | |
(:import [com.mchange.v2.c3p0 ComboPooledDataSource DataSources])) | |
(defn pool | |
[spec] | |
(let [cpds (doto (ComboPooledDataSource.) | |
(.setDriverClass (:classname spec)) | |
(.setJdbcUrl (str "jdbc:" (:subprotocol spec) ":" (:subname spec))) | |
(.setUser (:user spec)) | |
(.setPassword (:password spec)) | |
(.setMaxIdleTimeExcessConnections (* 30 60)) | |
(.setMaxIdleTime (* 3 60 60)))] | |
{:datasource cpds})) | |
(defrecord Database [db-spec connection] | |
component/Lifecycle | |
(start [this] | |
(println "Starting Database...") | |
(assoc this :connection (pool db-spec))) | |
(stop [this] | |
(DataSources/destroy (:datasource connection)) | |
(println "Database stopped.") | |
(assoc this :connection nil))) | |
(defn create-database [db-spec] | |
(map->Database {:db-spec db-spec})) | |
(defn wrap-app-component [f db] | |
(fn [req] | |
(f (assoc req :db db)))) | |
(defn make-handler [db] | |
(wrap-app-component app db)) | |
(defrecord HttpServer [database port http-server] | |
component/Lifecycle | |
(start [this] | |
(println "Starting HTTP server...") | |
(let [http-server (run-jetty (make-handler (:connection database)) | |
{:port port | |
:join? false})] | |
(println (str "You can view the site at http://localhost:" port)) | |
(assoc this :http-server http-server))) | |
(stop [this] | |
(.stop http-server) | |
(println "HTTP server stopped.") | |
(assoc this :http-server nil))) | |
(defn create-http-server [port] | |
(map->HttpServer {:port port})) | |
(defn create-system [{:keys [port db-spec] :as config-options}] | |
(component/system-map | |
:database (create-database db-spec) | |
:http-server (component/using | |
(create-http-server port) | |
[:database]))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment