Executing a function when starting a Ring / Compjure application after deployment

Possible duplicate:
How to start an arbitrary start function in a ring project?

I use clojure ring middleware, with compojure, to create a simple api. I often use the app as a war.

This works fine, but I'm looking at how to run one initialization code when the application starts. When I start the "lein ring server" server, it works very well, however when deployed as a war it only works when the first request hits the server (i.e. Lazy). Is there a way to make this not lazy (without using AOT) - or is there a better way to connect to the middleware life cycle?

+6
source share
2 answers

I think what you are looking for: init param in 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. 
+2
source

A ServletContextListener implementation will meet your needs. If you do not want you to execute it yourself with :gen-class , you can use the servlet utilities in the ring-java-servlet project.

To do this, create a file with the functions that you want to call 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 connect it to your webapp using 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> 
+1
source

Source: https://habr.com/ru/post/918456/


All Articles