Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build clojure application with ring server

I got clojure project with ring library in it. This is project.clj:

(defproject words "1.0.0-SNAPSHOT"
:description "Websocket handler for sessions"
:dependencies [[org.clojure/clojure "1.4.0"]
  [org.clojure/clojure-contrib "1.2.0"]
  [aleph "0.3.0-alpha1"]
  [org.clojure/data.json "0.1.2"]
  [clj-redis "0.0.13-SNAPSHOT"]
  [compojure "0.6.2"]
  [clj-http "0.1.3"]]
:main words.play
;; Lein ring plugin will provide `lein ring server` functionality
;; (and some other relative to ring actions)
:plugins [[lein-ring "0.6.6"]]
:ring {:handler words.api/engine})

In development environment I run it with 2 commands: lein run server lein ring server and it's works.

For production environment I want to minimize dependencies and build it into standalone jar with:

lein uberjar

How can I build it and run both of servers from one jar file?

like image 282
jurka Avatar asked Aug 22 '12 14:08

jurka


2 Answers

Regarding to

:main words.play

I advice you to implement -main function in words.play something like

(defn -main [& args]
  (case (first args)
    "server1" (do (println "Starting server1") (start-server1))
    "server2" (do (println "Starting server2") (start-server2))
    (println "Enter server name, pls")))

Note, that :gen-class is necessary in namespace definition:

(ns words.play
    (:gen-class))

Implementation for start-server1 and start-server2 should depend on concrete frameworks: (run-jetty ...) for ring, (start-http-server ...) for aleph and so on (you can find more info in relative documentation).

Usage:

lein uberjar
## to start first server
java -jar my-project-1.0.0-SNAPSHOT-standalone.jar server1
## to start second one
java -jar my-project-1.0.0-SNAPSHOT-standalone.jar server2
like image 55
Alexey Kachayev Avatar answered Sep 22 '22 21:09

Alexey Kachayev


The most straightforward approach is to pre-compile a class from a clojure source file that starts your application. Your -main function should ultimately call something like (run-jetty #'engine {:port 8080}).

Here's a good tutorial if you're not familiar with Clojure ahead-of-time compilation ("aot"): http://kotka.de/blog/2010/02/gen-class_how_it_works_and_how_to_use_it.html

Then it's a matter of creating a shell script that launches your application with something like java -cp you-uber.jar words.Main or somesuch.

Note that the name of your "app launcher" class and final jar name are completely arbitrary.

like image 29
noahlz Avatar answered Sep 20 '22 21:09

noahlz