Fast Clojure/Java Web Apps on NGINX Without a Java Web Server

Nginx-Clojure  is a Nginx module for embedding Clojure or Java programs, typically those Ring based handlers. It is an opensource project hosted on Github, the site url is HERE. With it we can develope high performance Clojure/Java web apps on Nginx without any Java web server and with several benefits:

There are three typical examples for writing a configuration about Ring handlers :


1. Pure Java Handler


package my;

import static nginx.clojure.MiniConstants.CONTENT_TYPE;
import static nginx.clojure.MiniConstants.NGX_HTTP_OK;

import java.io.IOException;
import java.util.Map;

import nginx.clojure.java.ArrayMap;
import nginx.clojure.java.NginxJavaRingHandler;

public class HelloHandler implements NginxJavaRingHandler {

@Override
public Object[] invoke(Map<String, Object> request) throws IOException {

return new Object[] { 
NGX_HTTP_OK, //http status 200
ArrayMap.create(CONTENT_TYPE, "text/plain"), //headers map
"Hello, Java & Nginx!"  //response body can be string, File or Array/Collection of string or File
};
}
}


In nginx.conf, eg.


location /java {
  content_handler_type java;
  content_handler_name my.HelloHandler;
 }



2. Inline Clojure Handler


       location /clojure {
          content_handler_code ' 
                        (fn[req]
                          {
                            :status 200,
                            :headers {"content-type" "text/plain"},
                            :body  "Hello Clojure & Nginx!" 
                            })
          ';
       }




3. External Clojure Handler


(ns my.hello)
(defn hello-world [request]
  {:status 200
  :headers {"Content-Type" "text/plain"}
  :body "Hello World"})



You should set your clojure JAR files to class path, see JVM path & class path from Nginx-Clojure Website.


       location /myClojure {
          content_handler_name 'my.hello/hello-world';
       }



For more details about the features from nginx-clojure please visit it Website https://nginx-clojure.github.io/ .

For more details and more useful examples for Compojure which is a small routing library for Ring that allows web applications to be composed of small, independent parts, please refer to https://github.com/weavejester/compojure

By the way the result of simple performance test with Nginx-Clojure is inspiring, more details can be got HERE  . Here 's the simple testing results , Nginx-Clojure is almost 6 times faster than Nginx-Php5


 

 

 

 

Top