Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing a function on ring/compjure application startup after deploy [duplicate]

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?

like image 254
Michael Neale Avatar asked Jun 19 '12 10:06

Michael Neale


2 Answers

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.
like image 67
DanLebrero Avatar answered Oct 14 '22 22:10

DanLebrero


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>
like image 29
Tim Clemons Avatar answered Oct 15 '22 00:10

Tim Clemons