Possible Duplicate:
How to run an arbitrary startup function in a ring project?
I am using the clojure ring middleware, with compojure, to build a simple api. I deploy the app often as a war.
This works great, but I am looking at ways to have one off initialisation code run when the app starts. When I run "lein ring server" it runs just fine - however, when deployed as a war it seems to only run when the first request hits the server (i.e. lazy). Is there a way to make it not be lazy (without using AOT) - or is there a better way to hook into ring middleware lifecycle?
I think you are looking for :init param in the lein-ring plugin. Copied from https://github.com/weavejester/lein-ring:
:init - A function to be called once before your handler starts. It should take no
arguments. If you've compiled your Ring application into a war-file, this function will
be called when your handler servlet is first initialized.
A ServletContextListener implementation would serve your needs. If you don't feel like implementing one yourself with :gen-class
, you can use the servlet utilities at the ring-java-servlet project.
To do so, create a file with the functions you wish called during startup and/or shutdown:
(ns my.project.init
(:require [org.lpetit.ring.servlet.util :as util]))
(defn on-startup [context]
(do-stuff (util/context-params context)))
(defn on-shutdown [context]
(do-other-stuff (util/context-params context)))
Then hook this into your webapp via the following web.xml
settings:
<context-param>
<param-name>context-init</param-name>
<param-value>my.project.init/on-startup</param-value>
</context-param>
<context-param>
<param-name>context-destroy</param-name>
<param-value>my.project.init/on-shutdown</param-value>
</context-param>
<listener>
<listener-class>org.lpetit.ring.servlet.RingServletContextListener</listener-class>
</listener>
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