-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathparams.json
1 lines (1 loc) · 29.7 KB
/
params.json
1
{"name":"nginx-clojure.github.io","tagline":"Nginx module for embedding Clojure / Java / Groovy programs, typically those Ring based handlers","body":"![Alt text](https://github.com/nginx-clojure/nginx-clojure/raw/master/logo.png)Nginx-Clojure is a [Nginx](http://nginx.org/) module for embedding Clojure or Java or Groovy programs, typically those [Ring](https://github.com/ring-clojure/ring/blob/master/SPEC) based handlers.\r\n\r\nThere are some core features :\r\n\r\n1. Compatible with [Ring](https://github.com/ring-clojure/ring/blob/master/SPEC) and obviously supports those Ring based frameworks, such as Compojure etc.\r\n1. Use Clojure / Java / Groovy(**_NEW_** ) to write simple ring handlers for http services.\r\n1. Use Clojure / Java / Groovy(**_NEW_** ) to write a simple nginx rewrite handler to set var or return errors before proxy pass or content ring handler\r\n1. Non-blocking coroutine based socket which is Compatible with Java Socket API and works well with largely existing java library such as apache http client, mysql jdbc drivers. \r\nWith this feature one java main thread can handle thousands of connections.\r\n1. Handle multiple sockets parallel in sub coroutines, e.g. we can invoke two remote services at the same time feature\r\n1. Asynchronous callback API of socket for some advanced usage\r\n1. Run initialization clojure code when nginx worker starting\r\n1. Support user defined http request method\r\n1. Compatible with the Nginx lastest stable version 1.6.0. (Nginx 1.4.x is also ok, older version is not tested and maybe works.)\r\n1. One of benifits of [Nginx](http://nginx.org/) is worker processes are automatically restarted by a master process if they crash\r\n1. Utilizes lazy headers and direct memory operation between [Nginx](http://nginx.org/) and JVM to fast handle dynamic contents from Clojure or Java code.\r\n1. Utilizes [Nginx](http://nginx.org/) zero copy file sending mechanism to fast handle static contents controlled by Clojure or Java code.\r\n1. Supports Linux x64, Linux x86 32bit, Win32 and Mac OS X. Win64 users can also run it with a 32bit JRE/JDK.\r\n\r\nBy the way it is very fast, the benchmarks can be found [HERE](https://github.com/ptaoussanis/clojure-web-server-benchmarks) .\r\n\r\n\r\n1. Installation\r\n=============\r\n\r\nThe lastest release is 0.2.4. Please check the [Update History](HISTORY.md) for more details.\r\n\r\n1.1 Installation by Binary\r\n-------------\r\n\r\n1. First you can download Release 0.2.4 from [here](https://sourceforge.net/projects/nginx-clojure/files/). \r\nThe zip file includes Nginx-Clojure binaries about Linux x64, Linux i586, Win32 and Mac OS X.\r\n1. Unzip the zip file downloaded then rename the file `nginx-${os-arc}` to `nginx`, eg. for linux is `nginx-linux-x64`\r\n\r\n\r\n1.2 Installation by Source\r\n-------------\r\n\r\nNginx-Clojure may be compiled successfully on Linux x64, Linux x86 32bit, Win32 and Mac OS X x64.\r\n\r\n1. First download from [nginx site](http://nginx.org/en/download.html) or check out nginx source by hg from http://hg.nginx.org/nginx. \r\nFor Win32 users MUST check out nginx source by hg because the zipped source doesn't contain Win32 related code.\r\n1. Check out Nginx-Clojure source from github OR download the zipped source code from https://github.com/xfeep/nginx-clojure/releases\r\n1. If you want to use Http SSL module, you should install openssl and openssl dev first.\r\n1. Setting Java header include path in nginx-clojure/src/c/config\r\n\r\n\t```nginx\r\n\t#eg. on ubuntu\r\n\tJNI_HEADER_1=\"/usr/lib/jvm/java-7-oracle/include\"\r\n\tJNI_HEADER_2=\"${JNI_HEADER_1}/linux\"\r\n\t````\r\n1. Add Nginx-Clojure module to Nginx configure command, here is a simplest example without more details about [InstallOptions](http://wiki.nginx.org/InstallOptions)\r\n\r\n\t```bash\r\n\t#If nginx source is checked out from hg, please replace ./configure with auto/configure\r\n\t$./configure \\\r\n\t\t--add-module=nginx-clojure/src/c\r\n\t$ make\r\n\t$ make install\r\n\t```\r\n1. Create the jar file about Nginx-Clojure\r\n\r\n\tPlease check the lein version `lein version`, it should be at least 2.0.0.\r\n\r\n\t```bash\r\n\t$ cd nginx-clojure\r\n\t$ lein jar\r\n\t```\r\n\tThen you'll find nginx-clojure-${version}.jar (eg. nginx-clojure-0.2.4.jar) in the target folder. \r\n\tThe jar file is self contained. If your project use clojure it naturally depends on the clojure core jar, e.g clojure-1.5.1.jar.\r\n\tIf your project use groovy it naturally depends on the groovy runtime jar, e.g. groovy-2.3.4.jar.\r\n\r\n2. Configurations\r\n=================\r\n\r\n2.1 JVM Path , Class Path & Other JVM Options\r\n-----------------\r\n\r\nSetting JVM path and class path within `http {` block in nginx.conf\r\n\r\n```nginx\r\n\r\n #for win32, jvm_path maybe is \"C:/Program Files/Java/jdk1.7.0_25/jre/bin/server/jvm.dll\";\r\n #for macosx, jvm_path maybe is \"/Library/Java/JavaVirtualMachines/1.6.0_65-b14-462.jdk/Contents/Libraries/libserver.dylib\";\r\n #for ubuntu, jvm_path maybe is \"/usr/lib/jvm/java-7-oracle/jre/lib/amd64/server/libjvm.so\";\r\n #for centos, jvm_path maybe is \"/usr/java/jdk1.6.0_45/jre/lib/amd64/server/libjvm.so\";\r\n #for centos 32bit, jvm_path maybe is \"/usr/java/jdk1.7.0_51/jre/lib/i386/server/libjvm.so\";\r\n \r\n jvm_path \"/usr/lib/jvm/java-7-oracle/jre/lib/amd64/server/libjvm.so\";\r\n \r\n #jvm_options can be repeated once per option.\r\n #for clojure, you should append clojure core jar, e.g -Djava.class.path=jars/nginx-clojure-0.2.4.jar:mypath-xxx/clojure-1.5.1.jar,please replace ':' with ';' on windows\r\n #for groovy, you should append groovy runtime jar, e.g. -Djava.class.path=jars/nginx-clojure-0.2.4.jar:mypath-xxx/groovy-2.3.4.jar, please replace ':' with ';' on windows\r\n jvm_options \"-Djava.class.path=jars/nginx-clojure-0.2.4.jar\";\r\n \r\n #jvm heap memory\r\n jvm_options \"-Xms1024m\";\r\n jvm_options \"-Xmx1024m\";\r\n \r\n #for enable java remote debug uncomment next two lines, make sure \"master_process = off;\" or \"worker_processes = 1;\"\r\n #jvm_options \"-Xdebug\";\r\n #jvm_options \"-Xrunjdwp:server=y,transport=dt_socket,address=8400,suspend=n\";\r\n````\r\n\r\n###Some Useful Tips\r\n\r\nThese tips are really useful. Most of them are from real users. Thanks [Rickr Nook](https://github.com/rickr-nook) who give us some useful tips.\r\n\r\n1. When importing Swing We Must specifiy `jvm_options \"-Djava.awt.headless=true\"` , otherwise the nginx will hang.\r\n1. By adding the location of your clojure source files to the classpath,then just issue \"nginx -s reload\" and changes to the sources get picked up!\r\n1. You can remove clojure-1.5.1.jar from class path and point at your \"lein uberjar\" to pick up a different version of clojure. \r\n1. To use Java 7 on OSX, in nginx.conf your may set `jvm_path \"/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/jre/lib/server/libjvm.dylib\";`\r\n\r\n2.2 Initialization Handler for nginx worker\r\n-----------------\r\n\r\nYou can embed clojure/groovy code in the `http { ` block to do initialization when nginx worker starting. e.g\r\n\r\n```nginx\r\nhttp {\r\n......\r\n handler_type 'clojure'; # or handler_type 'groovy'\r\n handler_code '....'; #the same with Ring Handler for Location (details in next section)\r\n....\r\n}\r\n```\r\nOr you can reference an exteranl clojure/java/groovy ring handler for initialization when nginx worker starting.\r\n\r\n```nginx\r\nhttp {\r\n......\r\n handler_type 'clojure'; # or handler_type 'java' / handler_type 'groovy'\r\n handler_name 'my.test/InitHandler'; # or for java it maybe 'my.test.MyJavaInitHandler'\r\n....\r\n}\r\n```\r\n\r\nThe ring handler can use status 500 and body to report some errors or just return nothing.\r\nFor more detail example of ring handler please see the next secion.\r\n\r\nPlease Keep these in your mind:\r\n\r\n* By default if the initialization failed the nginx won't start successfully and the worker will exit after reporting an error message in error log file but the master keep running and take the port.\r\n* Because the maybe more than one nginx worker processes, so this code will run everytime per worker starting. \r\n* If you use [SharedHashMap](https://github.com/OpenHFT/HugeCollections/wiki/Getting-Started) to share data \r\namong nginx worker processes, Java file lock can be used to let only one nginx worker process do the initialization.\r\n* If you enabled [coroutine support](#), nginx maybe will start successfully even if your initialization failed after some socket operations. If you case it, you can \r\nuse `nginx.clojure.core/without-coroutine` to wrap your handler, e.g.\r\n\r\nFor clojure\r\n\r\n```nginx\r\n\t handler_code '\r\n\t (do\r\n\t\t (use \\'nginx.clojure.core)\r\n\t\t (without-coroutine\r\n\t\t (fn[ctx]\r\n\t\t ....\r\n\t\t )\r\n\t\t ))\r\n\t ';\r\n```\r\n\r\n\r\n2.3 Ring Handler for Location\r\n-----------------\r\n\r\nWithin `location` block, \r\n* Directive `handler_type` is used to setting a type of handler.\r\n* Directive `handler_code` is used to setting an inline Ring handler.\r\n* Directive `handler_name` is used to setting an external Ring handler which is in a certain jar file included by your classpath.\r\n\r\n\r\n###2.3.1 Inline Ring Handler\r\n\r\nFor Clojure : \r\n\r\n```nginx\r\n location /clojure {\r\n handler_type 'clojure';\r\n handler_code ' \r\n\t\t\t\t\t\t(fn[req]\r\n\t\t\t\t\t\t {\r\n\t\t\t\t\t\t :status 200,\r\n\t\t\t\t\t\t :headers {\"content-type\" \"text/plain\"},\r\n\t\t\t\t\t\t :body \"Hello Clojure & Nginx!\" ;response body can be string, File or Array/Collection/Seq of them\r\n\t\t\t\t\t\t })\r\n ';\r\n }\r\n```\r\nNow you can start nginx and access http://localhost:8080/clojure, if some error happens please check error.log file. \r\n\r\nFor Groovy :\r\n\r\n```nginx\r\n location /groovy {\r\n handler_type 'groovy';\r\n handler_code ' \r\n import nginx.clojure.java.NginxJavaRingHandler;\r\n import java.util.Map;\r\n public class HelloGroovy implements NginxJavaRingHandler {\r\n public Object[] invoke(Map<String, Object> request){\r\n return [200, //http status 200\r\n [\"Content-Type\":\"text/html\"], //headers map\r\n \"Hello, Groovy & Nginx!\"]; //response body can be string, File or Array/Collection of them\r\n }\r\n }\r\n ';\r\n }\r\n```\r\n\r\nNow you can start nginx and access http://localhost:8080/groovy, if some error happens please check error.log file. \r\n\r\n\r\n###2.3.2 Reference of External Ring Handlers\r\n\r\nPlease make sure the external Ring handler is in a certain jar file or a directory included by your classpath.\r\nIt is also OK if you do not compile the Clojure/Groovy to java class file and just put the source of them in a certain jar file or a directory included by your classpath. \r\n\r\nFor Clojure the exteranl Ring handler example is here\r\n\r\n```clojure\r\n(ns my.hello)\r\n(defn hello-world [request]\r\n {:status 200\r\n :headers {\"Content-Type\" \"text/plain\"}\r\n ;response body can be string, File or Array/Collection/Seq of them\r\n :body \"Hello World\"})\r\n\r\n```\r\nThen we can reference it in nginx.conf\r\n\r\n```nginx\r\n location /myClojure {\r\n handler_type 'clojure';\r\n handler_name 'my.hello/hello-world';\r\n }\r\n```\r\nFor more details and more useful examples for [Compojure](https://github.com/weavejester/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\r\n\r\nFor Java\r\n\r\n```java\r\npackage mytest;\r\nimport static nginx.clojure.MiniConstants.*;\r\n\r\nimport java.util.HashMap;\r\nimport java.util.Map;\r\npublic class Hello implements NginxJavaRingHandler {\r\n\r\n\t\t@Override\r\n\t\tpublic Object[] invoke(Map<String, Object> request) {\r\n\t\t\treturn new Object[] { \r\n\t\t\t\t\tNGX_HTTP_OK, //http status 200\r\n\t\t\t\t\tArrayMap.create(CONTENT_TYPE, \"text/plain\"), //headers map\r\n\t\t\t\t\t\"Hello, Java & Nginx!\" //response body can be string, File or Array/Collection of them\r\n\t\t\t\t\t};\r\n\t\t}\r\n\t}\r\n```\r\n\r\n```nginx\r\n location /myJava {\r\n handler_type 'java';\r\n handler_name 'mytest.Hello';\r\n }\r\n```\r\n\r\nFor Groovy\r\n\r\n```groovy\r\n package mytest;\r\n import nginx.clojure.java.NginxJavaRingHandler;\r\n import java.util.Map;\r\n public class HelloGroovy implements NginxJavaRingHandler {\r\n public Object[] invoke(Map<String, Object> request){\r\n return \r\n [200, //http status 200\r\n [\"Content-Type\":\"text/html\"],//headers map\r\n \"Hello, Groovy & Nginx!\" //response body can be string, File or Array/Collection of them\r\n ]; \r\n }\r\n }\r\n```\r\n\r\n###2.3.3 Pure Java Handler\r\n\r\nThe section is **__deprecated__**. Please check the above section and use new derective `handler_type` and `handler_name` for easier work.\r\n\r\n```java\r\npackage my;\r\n\r\nimport nginx.clojure.Constants;\r\nimport clojure.lang.AFn;\r\nimport clojure.lang.IPersistentMap;\r\nimport clojure.lang.PersistentArrayMap;\r\n\r\npublic class HelloHandler extends AFn {\r\n\t\r\n\t@Override\r\n\tpublic Object invoke(Object r) {\r\n\t\tIPersistentMap req = (IPersistentMap)r;\r\n\t\t\r\n\t\t//get some info from req. eg. req.valAt(Constants.QUERY_STRING)\r\n\t\t//....\r\n\t\t\r\n\t\t//prepare resps, more details about Ring handler on this site https://github.com/ring-clojure/ring/blob/master/SPEC\r\n\t\tObject[] resps = new Object[] {Constants.STATUS, 200, \r\n\t\t\t\tConstants.HEADERS, new PersistentArrayMap(new Object[]{Constants.CONTENT_TYPE.getName(),\"text/plain\"}),\r\n\t\t\t\tConstants.BODY, \"Hello Java & Nginx!\"};\r\n\t\treturn new PersistentArrayMap(resps);\r\n\t}\r\n\t\r\n}\r\n```\r\n\r\n\r\nIn nginx.conf, eg.\r\n\r\n```nginx\r\n\tlocation /java {\r\n clojure;\r\n clojure_code ' \r\n (do (import \\'[my HelloHandler]) (HelloHandler.) )\r\n ';\r\n }\r\n```\r\n\r\nYou should set your JAR files to class path, see [2.1 JVM Path , Class Path & Other JVM Options](#21-jvm-path--class-path--other-jvm-options) .\r\n\r\n2.4 Chose Coroutine based Socket Or Asynchronous Socket Or Thread Pool for slow I/O operations\r\n-----------------\r\n\r\nIf the http service should do some slow I/O operations such as access external http service, database, etc. nginx worker will be blocked by those operations \r\nand the new user request even static file request will be blocked. It really sucks! Before v0.2.0 the only choice is using thread pool but now we have \r\nthree choice :\r\n\r\n1. Coroutine based Socket\r\n\t* :smiley:It's Java Socket API Compatible and work well with largely existing java library such as apache http client, mysql jdbc drivers etc.\r\n\t* :smiley:It's non-blocking, cheap, fast and let one java main thread be able to handle thousands of connections.\r\n\t* :smiley:Your old code **_need not be changed_** and those plain and old java socket based code such as Apache Http Client, MySQL mysql jdbc drivers etc. will be on the fly with epoll/kqueue on Linux/BSD!\r\n\t* :worried:You must do some steps to get the right class waving configuration file and set it in the nginx conf file.\r\n1. Asynchronous Socket\r\n\t* :smiley:It's the fastest among those three choice and you can controll it finely.\r\n\t* :smiley:It can work with default mode or Coroutine based Socket enabled mode but can't work with Thread Pool mode.\r\n\t* :worried:Your old code **_must be changed_** to use the event driven pattern.\r\n1. Thread Pool\r\n\t* :smiley:It's a trade off choice and almost all Java server such as Jetty, Tomcat , Glassfish etc. use thread pool to handle http requests.\r\n\t* :smiley:Your old code **_need not be changed_**.\r\n\t* :worried:The nginx worker will be blocked after all threads are exhuasted by slow I/O operations.\r\n\t* :worried:Becase the max number of threads is alwarys more smaller than the total number of socket connections supported by Operation Systems and\r\nthread in java is costlier than coroutine, facing large amount of connections this choice isn't as good as Coroutine based choice.\r\n\r\n### 2.4.1 Enable Coroutine based Socket\r\n\r\n#### 1. Get a User Defined Class Waving Configuration File for Your Web App\r\n\r\n* Turn on Run Tool Mode\r\n\t\t\r\n\t```nginx\r\n\thttp {\r\n\t...\r\n\t\r\n\t#To make sure generated Class Waving Configuration File won't be mixed by many workers. \r\n\tworker_processes 1;\r\n\t\r\n\t#turn on run tool mode, t means Tool\r\n\tjvm_options \"-javaagent:jars/nginx-clojure-0.2.4.jar=tmb\";\r\n\t\r\n\t#for clojure, you should append clojure core jar, e.g -Djava.class.path=jars/nginx-clojure-0.2.4.jar:mypath-xxx/clojure-1.5.1.jar,please replace ':' with ';' on windows\r\n jvm_options \"-Xbootclasspath/a:jars/nginx-clojure-0.2.4.jar\";\r\n ...\r\n\t}\r\n\t```\r\n* Setting Output Path of Waving Configuration File\r\n\t\r\n\t```nginx\r\n\t#Optional The default value is $nginx-workdir/nginx.clojure.wave.CfgToolOutFile\r\n\t#Setting Output Path of Waving Configuration File, \r\n jvm_options \"-Dnginx.clojure.wave.CfgToolOutFile=/tmp/my-wave-cfg.txt\";\r\n\t```\r\n* Setting Dump Configuration Service\r\n\r\n\t```nginx\r\n location /dump {\r\n handler_type 'java';\r\n handler_name 'nginx.clojure.java.WaveConfigurationDumpHandler'; \r\n }\r\n\t```\r\n* Start Nginx which Compiled with Nginx Clojure Module\r\n* Run curl or httpclient based junit tests to access your http services which directly or indirectly use Java Socket API, e.g Apache Http Client, MySQL JDBC Driver etc.\r\n* After All responses completed We'll get a generated class waving configuration file e.g `my-wave-cfg.txt` by access Dump Configuration Service.\r\n\r\n\t```bash\r\n\t/*use curl or just put the Dump Service url to browser and click GO!\r\n\t *Dump Service will generate Waving Configuration File to the path defined by \r\n\t *java system property `nginx.clojure.wave.CfgToolOutFile`\r\n\t */\r\n\tcurl -v http://localhost:8080/dump\r\n\t```\r\n\t\r\n\tDon't foget reset `worker_processes` and turn off run tool mode for product enviroument after get class waving configuration\r\n\t\r\n#### 2. Enable Coroutine Support\r\n\r\n* Turn on Coroutine Support\r\n\r\n\t```nginx\r\n\thttp {\r\n\t...\r\n\t#make sure it is reset to a normal number after above step, e.g. 8 worker processes.\r\n\tworker_processes 8;\r\n\t\t\t\r\n\t#turn on coroutine mode\r\n\tjvm_options \"-javaagent:jars/nginx-clojure-0.2.4.jar=mb\";\r\n\t\r\n\t#append nginx-clojure & clojure runtime jars to jvm bootclasspath \t\t\r\n\t#for win32, class path seperator is \";\", e.g \"-Xbootclasspath/a:jars/nginx-clojure-0.2.4.jar;jars/clojure-1.5.1.jar\"\r\n\tjvm_options \"-Xbootclasspath/a:jars/nginx-clojure-0.2.4.jar:jars/clojure-1.5.1.jar\";\r\n\t\r\n\t#coroutine-udfs is a directory to put your User Defined Class Waving Configuration File\r\n\t#for win32, class path seperator is \";\", e.g \"-Djava.class.path=coroutine-udfs;YOUR_CLASSPATH_HERE\"\r\n\t#Note: DON NOT put nginx-clojure & clojure runtime jars here, because they have been appened to the jvm bootclasspath\r\n\tjvm_options \"-Djava.class.path=coroutine-udfs:YOUR_CLASSPATH_HERE\";\r\n\t\r\n\t\r\n\t#copy the waving configuration file generated from previous step to you any classpath dir e.g. coroutine-udfs\r\n\t#setting user defined class waving configuration files which are in the above boot classpath, the seperator is \",\" \r\n\tjvm_options \"-Dnginx.clojure.wave.udfs=my-wave-cfg.txt\";\r\n\t...\r\n\t}\r\n\t```\r\n\t\r\n* restart nginx or reload nginx\r\n\t\r\n\tNow every nginx worker can handle thousands of connections easily! \r\n\t\r\n\tThose plain and old java socket based code such as Apache Http Client, MySQL mysql jdbc drivers etc. will be on the fly with epoll/kqueue on Linux/BSD!\r\n\t\r\n\tNginx won't blocked until nginx connections exhuasted or jvm OutOfMemory!\r\n\r\n### 2.4.2 Use Asynchronous Socket\r\n\r\nAsynchronous Socket Can be used with default mode or coroutined enabled mode without any additional settings. It just a set of API.\r\nIt uses event driven pattern and works with a java callback handler or clojure function for callback.\r\nPlease check the source code and examples for more details.\r\n\r\n* source: [nginx.clojure.net.NginxClojureAsynSocket](src/java/nginx/clojure/net/NginxClojureAsynSocket.java)\r\n* example: \r\n\t* Java [nginx.clojure.net.SimpleHandler4TestNginxClojureAsynSocket](test/java/nginx/clojure/net/SimpleHandler4TestNginxClojureAsynSocket.java)\r\n\t* Clojure [nginx.clojure.asyn-socket-handlers-for-test](test/clojure/nginx/clojure/asyn_socket_handlers_for_test.clj)\r\n\r\nIn future we'll give more clojure style wrapper and examples. **_Pull requests are also welcome!_**\r\n\r\n### 2.4.3 Use Thread Pool\r\n\r\nIf your tasks are often blocked by slow I/O operations, the thread pool method can make the nginx worker not blocked until\r\nall threads are exhuasted. When facing large amount of connections this choice isn't as good as above coroutine based choice or asynchronous socket.\r\n\r\neg.\r\n\r\n```nginx\r\n\r\n#turn off coroutine mode, n means do nothing. You can also comment this line to turn off coroutine mode \r\njvm_options \"-javaagent:jars/nginx-clojure-0.2.4.jar=nmb\";\r\n\r\njvm_workers 40;\r\n```\r\nNow Nginx-Clojure will create a thread pool with fixed 40 threads per JVM instance/Nginx worker to handle requests. If you get more memory, you can set\r\na bigger number.\r\n\r\n2.5 Nginx rewrite handler\r\n-----------------\r\n\r\nA nginx rewrite handler can be used to set var or return errors before proxy pass or content ring handler. \r\nIf the rewrite handler returns `phrase-done` (Clojure) or `PHRASE_DONE` (Groovy/Java), nginx will continue to invoke proxy_pass or \r\ncontent ring handler.\r\nIf the rewrite handler returns a general response, nginx will send this response to the client and stop to continue to invoke proxy_pass or \r\ncontent ring handler.\r\n\r\n### 2.5.1 Simple Example about Nginx rewrite handler\r\n\r\nHere's a simple clojure example for Nginx rewrite handler :\r\n\r\n```nginx\r\n\r\n set $myvar \"\";\r\n \r\n location /rewritesimple {\r\n handler_type 'clojure';\r\n handler_rewrite_code '\r\n (do (use \\'[nginx.clojure.core]) \r\n\t\t\t\t\t\t(fn[req]\r\n\t\t\t\t\t\t (set-ngx-var! req \"myvar\" \"Hello\")\r\n\t\t\t\t\t\t phrase-done))\r\n ';\r\n handler_code '\r\n (do (use \\'[nginx.clojure.core]) \r\n\t\t\t\t\t\t(fn[req]\r\n\t\t\t\t\t\t (set-ngx-var! req \"myvar\" \r\n\t\t\t\t\t\t (str (get-ngx-var req \"myvar\") \",\" \"Xfeep!\"))\r\n\t\t\t\t\t\t {\r\n\t\t\t\t\t\t :status 200,\r\n\t\t\t\t\t\t :headers {\"content-type\" \"text/plain\"},\r\n\t\t\t\t\t\t :body (get-ngx-var req \"myvar\") \r\n\t\t\t\t\t\t }))\r\n ';\r\n } \r\n\r\n```\r\n\r\n### 2.5.2 Simple Dynamic Balancer By Nginx rewrite handler\r\n\r\nWe can alos use this feature to complete a simple dynamic balancer , e.g.\r\n\r\n```nginx\r\n\r\n set $myhost \"\";\r\n \r\n location /myproxy {\r\n handler_type 'clojure';\r\n handler_rewrite_code '\r\n (do (use \\'[nginx.clojure.core]) \r\n\t\t\t\t\t\t(fn[req]\r\n\t\t\t\t\t\t ;compute myhost (upstream name or real host name) based req & remote service, e.g.\r\n\t\t\t\t\t\t (let [myhost (compute-myhost req)])\r\n\t\t\t\t\t\t (set-ngx-var! req \"myhost\" myhost)\r\n\t\t\t\t\t\t phrase-done))\r\n ';\r\n proxy_pass $myhost\r\n } \r\n\r\n```\r\n\r\nThe equivalent java code is here\r\n\r\n```java\r\n\r\npackage my.test;\r\n\r\nimport static nginx.clojure.java.Constants.*;\r\n\t\r\n\tpublic static class MyRewriteProxyPassHandler implements NginxJavaRingHandler {\r\n\t\t@Override\r\n\t\tpublic Object[] invoke(Map<String, Object> req) {\r\n\t\t\tString myhost = computeMyHost(req);\r\n\t\t\tNginxClojureRT.setNGXVariable(req.nativeRequest(), \"myhost\", myhost);\r\n\t\t\treturn PHRASE_DONE;\r\n\t\t}\r\n\t\t\r\n\t\tprivate String computeMyHost(Map<String, Object> req) {\r\n\t\t\t//compute a upstream name or host name;\r\n\t\t}\r\n\t}\r\n\r\n```\r\nThen we set the java rewrtite handler in nginx.conf\r\n\r\n```nginx\r\n\r\n set $myhost \"\";\r\n \r\n location /myproxy {\r\n handler_type 'java';\r\n handler_rewrite_name 'my.test.MyRewriteProxyPassHandler';\r\n proxy_pass $myhost\r\n } \r\n\r\n```\r\n\r\n### 2.5.3 Simple Access Controller By Nginx rewrite handler\r\n\r\nFor clojure\r\n\r\n```nginx\r\n handler_type 'clojure';\r\n handler_rewrite_code '\r\n (do (use \\'[nginx.clojure.core]) \r\n (import \\'[com\\.test AuthenticationHandler]) \r\n (fn[req]\r\n (if ((AuthenticationHandler.) req)\r\n ;AuthenticationHandler returns true so we go to proxy_pass\r\n phrase-done \r\n ;else return 403\r\n {:status 403}\r\n )))\r\n ';\r\nproxy_pass http://localhost:8084;\r\n```\r\n\r\nFor Java\r\n* nginx.conf\r\n \r\n\t```nginx\r\n\t\thandler_type 'java';\r\n\t\thandler_rewrite_name 'com.test.MyHandler';\r\n\t\tproxy_pass http://localhost:8084;\r\n\t```\r\n\t\t\r\n* MyHandler.java\r\n \r\n\t```java\r\npackage com.test;\r\nimport static nginx.clojure.java.Constants.*;\r\npublic class MyHandler implements NginxJavaRingHandler {\r\n\t\r\n\t\tpublic Object[] invoke(Map<String,Object> req) {\r\n\t\t\r\n\t\t /*do some computing here*/\r\n\t\t \r\n\t\t if (goto-proxy-pass) {\r\n\t\t return PHRASE_DONE;\r\n\t\t }else { //return 403\r\n\t\t return Object[] resps = new Object[] {\r\n\t\t Constants.STATUS, 403, \r\n\t\t //add some headers -- optional for no-20X response\r\n\t\t //Constants.HEADERS, nginx.clojure.java.ArrayMap.create(new Object[]{CONTENT_TYPE,\"text/plain\"}),\r\n\t\t //body text -- optional for no-20X response\r\n\t\t // Constants.BODY, \"xxxxxxxxxxxxxx!\"\r\n\t\t };\r\n\t\t }\r\n\t\t}\r\n\t\r\n\t```\r\n\r\n3. More about Nginx-Clojure\r\n=================\r\n\r\n3.1 Handle Multiple Coroutine Based Sockets Parallel\r\n-----------------\r\n\r\nSometimes we need to invoke serveral remote services before completing the ring response. For better performance we need a way to handle multiple sockets parallel in sub coroutines.\r\n\r\ne.g. fetch two page parallel by clj-http\r\n\r\n```clojure\r\n (let [[r1, r2] \r\n (co-pvalues (client/get \"http://service1-url\") \r\n (client/get \"http://service2-url\"))]\r\n ;println bodies of two remote response\r\n (println (str (:body r1) \"====\\n\" (:body r2) ))\r\n```\r\n\r\nHere `co-pvalues` is also non-blocking and coroutine based. In fact it will create two sub coroutines to handle two sockets.\r\n\r\nFor Java/Groovy, we can use `NginxClojureRT.coBatchCall` to do the same thing. Here's a simple example for Groovy.\r\n\r\n```groovy\r\n def (r1, r2) = NginxClojureRT.coBatchCall( \r\n {\"http://mirror.bit.edu.cn/apache/httpcomponents/httpclient/\".toURL().text},\r\n {\"http://mirror.bit.edu.cn/apache/httpcomponents/httpcore/\".toURL().text})\r\n return [200, [\"Content-Type\":\"text/html\"], r1 + r2];\r\n\r\n```\r\n\r\n3.2 Shared Map among Nginx Workers\r\n-----------------\r\n\r\nGenerally use redis or memorycached is the better choice to implement a shared map among Nginx workers. We can do some initialization of the \r\nshared map by following the guide of [2.2 Initialization Handler for nginx worker](#22-initialization-handler-for-nginx-worker).\r\nIf you like shared map managed in nginx process better than redis or memcached, you can choose [SharedHashMap](https://github.com/OpenHFT/HugeCollections/wiki) \r\nwhich is fast and based on Memory Mapped File so that it can store large amout of records and won't need too much java heap memory.\r\n\r\n3.3 User Defined Http Method\r\n-----------------\r\n\r\nSome web services need a user defined http request method to define special operations beyond standard http request methods. \r\n\r\ne.g. We use `MYUPLOAD` to upload a file and overwrite the one if it exists. The `curl` command could be \r\n\r\n```bash\r\ncurl -v -X MYUPLOAD --upload-file post-test-data \\\r\n\"http://localhost:8080/myservice\" \r\n```\r\n\r\nIn the nginx.conf, we can use `always_read_body on;` to force nginx to read http body.\r\n\r\n```nginx\r\n\r\nlocation /myservice {\r\n handler_type 'clojure';\r\n always_read_body on;\r\n handler_code '....';\r\n}\r\n\r\n```\r\n\r\n\r\n4. Useful Links\r\n=================\r\n\r\n* [Ring Documents](https://github.com/ring-clojure/ring/wiki)\r\n* [Comojure Documents](https://github.com/weavejester/compojure/wiki)\r\n* [Simple Examples](test/nginx-working-dir/conf/nginx.conf) in Nginx Clojure Testing Configuration & [Testing Client Code](test/clojure/nginx/clojure/test_all.clj)\r\n* [Nginx Clojure Ring Handlers Examples for Testing](test/clojure/nginx/clojure/ring_handlers_for_test.clj) (Testing with Ring Core 1.2.1)\r\n\r\n\r\n5. License\r\n=================\r\nCopyright © 2013-2014 Zhang, Yuexiang (xfeep) and released under the BSD 3-Clause license.\r\n\r\nThis program uses:\r\n* Re-rooted ASM bytecode engineering library which is distributed under the BSD 3-Clause license\r\n* Modified Continuations Library Written by Matthias Mann is distributed under the BSD 3-Clause license\r\n","google":"UA-53526038-1","note":"Don't delete this file! It's used internally to help with page regeneration."}