Last active
August 29, 2015 14:05
-
-
Save matstani/d46e1929d1419547ed5c to your computer and use it in GitHub Desktop.
HttpServerコンポーネントはDatabaseコンポーネントを利用する
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 example-component-ring.component | |
(:require [com.stuartsierra.component :as component] | |
[monger.core :as mg] | |
[example-component-ring.handler :refer [app]] | |
[ring.adapter.jetty :refer [run-jetty]])) | |
;; データベースコンポーネント | |
(defrecord Database [connection] | |
component/Lifecycle | |
(start [this] | |
(if connection | |
this | |
(do (println ";; Starting database") | |
(let [conn (mg/connect)] | |
(assoc this :connection conn))))) | |
(stop [this] | |
(if (not connection) | |
this | |
(do (try (mg/disconnect connection) | |
(catch Throwable t | |
";; Error when stopping database")) | |
(println ";; Database stopped") | |
(assoc this :connection nil))))) | |
;; データベースコンポーネントの作成用関数 | |
(defn create-database [] | |
(map->Database {})) | |
;; HTTPサーバコンポーネント | |
(defrecord HttpServer [port server database] | |
component/Lifecycle | |
(start [this] | |
(if server | |
this | |
(do (println ";; Starting HTTP server") | |
(let [server (run-jetty app | |
{:port port | |
:join? false})] | |
(assoc this :server server))))) | |
(stop [this] | |
(if (not server) | |
this | |
(do (try (.stop server) | |
(catch Throwable t | |
(print ";; Error when stopping HTTP server"))) | |
(println ";; HTTP server stopped") | |
(assoc this :server nil))))) | |
;; HTTPサーバコンポーネントの作成用関数 | |
(defn create-http-server [port] | |
(map->HttpServer {:port port})) | |
;; システム作成用関数 | |
(defn create-system [config-options] | |
(let [{:keys [port]} config-options] | |
(component/system-map | |
:database (create-database) | |
: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