精選版:用Java擴展Nginx(nginx-clojure 入門)

歡迎訪問我的GitHub

這裏分類和彙總了欣宸的全部原創(含配套源碼):https://github.com/zq2599/blog_demos

本篇概覽

  • 今天咱們以Java程序員的視角,來聊聊如何用Java來擴展Nginx的能力,全文由以下內容組成:
  1. 什麼是Nginx
  2. 什麼是Nginx擴展
  3. 擴展Nginx,意義何在?
  4. 想用Java擴展Nginx會有問題嗎?
  5. 主角登場:nginx-clojure模塊,讓Java擴展Nginx成爲顯示
  • 總的來說這是一篇從概念到實踐的入門文章,接下來,一起開始愉快的nginx-clojure之旅吧!

關於Nginx

  • 以欣宸自己爲例,nginx對java程序員來說並不陌生,下圖應該是最常見的使用場景了:反向代理
    在這裏插入圖片描述

關於Nginx擴展

  • 除了反向代理,nginx的模塊化機制讓nginx具備了更多豐富的特性,例如ngx_http_log_module(日誌)、ngx_http_rewrite_module(重定向)等
  • 除了官方模塊,還有很多強大第三方模塊可以選擇,如下圖,更多詳情參考:https://www.nginx.com/resources/wiki/modules/
    在這裏插入圖片描述
  • 大名鼎鼎的OpenResty就是基於 Nginx 擴展的,用Lua做二次開發web功能,得到了廣泛的應用
  • 如此看來,在nginx上做二次開發並非神祕高深莫測,我們也可以按照自己的需要去定製和擴展nginx的功能
  • 作爲一名Java程序員,自然就想到了:可以用Java去擴展Nginx的能力嗎?

爲什麼要用java對nginx擴展?

  • 把java代碼寫在nginx上,讓nginx與業務耦合的可能性變大,經驗豐富的您一定會發現這是個危險的趨勢,畢竟nginx已經接近後臺服務的最外層了,穩定是首要考慮的,正常情況下,下圖這種用法纔是生產環境的常見fang方案:將nginx作爲反向代理,業務功能獨立部署
    在這裏插入圖片描述
  • 這麼看來,在nginx上寫java代碼是否合適呢?欣宸給不出權威答案,但是可以從大神的作品中得到啓示
  • 開濤大神的《跟我學Nginx+Lua開發》講述瞭如何用OpenResty在Nginx上用Lua進行開發,適用於web應用、接入網關、Web防火牆、緩存服務器等場景下,並且在實體書《億級流量網站架構核心技術》也有詳細說明,例如京東商品詳情頁,就是在nginx上讀取緩存直接返回的
  • 綜上所述,欣宸不會因爲學習了這個技術,就把業務邏輯全部在nginx上實現,但是在緩存、鑑權等場景,可以考慮用熟悉的java在nginx上實現

Java程序員的尷尬

  • 定製Nginx,打造高性能Web服務,帶着這個美好憧憬,我打開了有關模塊開發的Nginx官方資料
  • 然後,畫風開始劇變,而且是朝着我不想面對的方向,如下圖
    在這裏插入圖片描述
  • 模塊開發用的居然是C語言!然而,欣宸只是個精通CRUD的Java程序員
  • 這可怎麼辦?隨手打開一個網頁就讓夢想破滅?

nginx-clojure,讓Java擴展nginx成爲現實

  • 經過一番搜索,終於找到了nginx-clojure模塊,如下圖,是它讓java擴展nginx成爲現實
    在這裏插入圖片描述
  • nginx-clojure的作用很好理解:OpenResty支持用Lua擴展nginx,nginx-clojure支持用Java擴展nginx
  • nginx-clojure的作用很好理解:OpenResty支持用Lua擴展nginx,nginx-clojure支持用Java擴展nginx

關於nginx-clojure

  • nginx-clojure是個第三方Nginx模塊,官方的介紹是Nginx module for embedding Clojure / Java / Groovy programs, typically those Ring based handlers
  • nginx-clojure模塊支持嵌入式Clojure(閉包)、Java、Groovy等基於Ring的處理器(handler),那什麼是Ring呢?
  • Ring 在 Clojure 中是一個構建 Web 應用的底層接口和庫. 它和 Ruby 的 Rack, Python 裏面的WSGI 或者 Java Servlet 規範相似
  • 從java開發者角度來看,就是開發NginxJavaRingHandler的實現類,然後該類可以在nginx-clojure模塊中被運行
  • nginx-clojure的最新版本是v0.5.2,官網地址是:https://nginx-clojure.github.io

實戰功能介紹

  • 儘管nginx-clojure支持很多功能,但是篇幅所限,因此本篇以瞭解爲主,還是經典的Hello world,更多精彩內容留給後續的系列文章
  • 今天的實戰效果如下圖,咱們編寫HelloHandler.java並在nginx做好配置,然後用瀏覽器發起請求後,HelloHandler的代碼就會被執行,瀏覽器會收到HelloHandler返回的內容,這就證實了java代碼可以在nginx上運行:
    在這裏插入圖片描述
  • 爲了實現上述功能,接下來的操作步驟如下圖:
    在這裏插入圖片描述
  • 感謝您聽我嘮叨了這麼久,接下來,實戰開始

環境信息

  • 這裏給出我的實戰環境信息供您參考,這個環境可以正常運行所有實戰:
  1. 操作系統:macOS Big Sur 11.5.2 (20G95)
  2. JDK:1.8.0_281
  3. Maven:3.8.1

下載集成了nginx-clojure模塊的nginx包

  • 咱們要做的第一件事是下載一個特別的nginx,之所以說它特別,是因爲它已集成了nginx-clojure模塊,開箱即用
  • 下載地址:https://sourceforge.net/projects/nginx-clojure/files/ ,如下圖紅框,我這裏選擇的是最新的0.5.2版本:
    在這裏插入圖片描述

解壓nginx包

  • 下載完畢後,解壓,得到名爲nginx-clojure-0.5.2的文件夾,裏面的內容如下
    在這裏插入圖片描述
  • 接下來根據您的操作系統對可執行文件做重命名,我這邊是macOS,所以把nginx-macosx重命名爲nginx,如果是linux,把nginx-linux-64重命名爲nginx,如果是windows,就把nginx-win64.exe重命名爲nginx.exe
  • 上述重命名操作是nginx-clojure官方推薦的,統一可執行文件名,這樣運行文檔中的命令就統一了
  • 執行命令./nginx -v,控制檯響應如下,可見nginx版本是1.18.0:
./nginx -v
nginx version: nginx/1.18.0

編碼,開發java版handler

  • 接下來開始寫代碼,先新建一個maven工程(我這裏名叫simple-hello),pom.xml中需要配置repository節點,以及唯一的依賴nginx-clojure,如下所示:
<repositories>
  <repository>
    <id>clojars.org</id>
    <url>http://clojars.org/repo</url>
    </repository>
</repositories>

<dependencies>
  <dependency>
    <groupId>nginx-clojure</groupId>
    <artifactId>nginx-clojure</artifactId>
    <version>0.5.2</version>
  </dependency>
</dependencies>
  • 然後新增文件HelloHandler.java,如下所示,代碼非常簡單,實現NginxJavaRingHandler接口,invoke方法返回的數組中只有三個元素:返回碼、響應header的鍵值對集合、響應body內容:
package com.bolingcavalry.simplehello;

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

import java.time.LocalDateTime;
import java.util.Map;

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

/**
 * @author [email protected]
 * @Title: 產生內容的handler
 * @Package
 * @Description:
 * @date 2/1/22 12:41 PM
 */
public class HelloHandler implements NginxJavaRingHandler {

    @Override
    public Object[] invoke(Map<String, Object> request) {
        return new Object[] {
                NGX_HTTP_OK, //http status 200
                ArrayMap.create(CONTENT_TYPE, "text/plain"), //headers map
                "Hello, Nginx clojure! " + LocalDateTime.now()  //response body can be string, File or Array/Collection of them
        };
    }
}
  • 至此,編碼完成,欣宸精通Hello World果然並非空穴來風…

編譯,生成jar

  • 在pom.xml所在目錄執行編譯構建的命令mvn clean package -U,會在target目錄下生成jar包,只有3K大小:
    在這裏插入圖片描述

jar放入nginx的jars目錄

  • 將前面生成的simple-hello-1.0-SNAPSHOT.jar文件放入下圖紅框的jars文件夾內
    在這裏插入圖片描述

修改nginx的配置

  • 打開nginx-clojure-0.5.2/conf/nginx.conf文件,在server配置中增加一個location配置,內容如下,指定了handler類型,以及對應的java類:
location /java {
         content_handler_type 'java';
         content_handler_name 'com.bolingcavalry.simplehello.HelloHandler';
}
  • 修改後,完整的nginx.conf內容如下,可見有很多java相關的配置,在本篇咱們都保持不動,留待後面的文章解鎖:
###you can uncomment next two lines for easy debug
###Warning: if master_process is off, there will be only one nginx worker running. Only use it for debug propose.

#daemon  off;

#master_process  off;

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
    

    jvm_path auto;
    
    ### Set my app jars and resources, it must include nginx-clojure runtime jar,e.g. nginx-clojure-0.5.1.jar and 
    ### for clojure user clojure runtime jar is also needed.
    ### See http://nginx-clojure.github.io/directives.html#jvm_classpath
    jvm_classpath "libs/*:jars/*";
    
    ###jvm heap memory
    #jvm_options "-Xms1024m";
    #jvm_options "-Xmx1024m";
    
    #for enable java remote debug uncomment next two lines
    #jvm_options "-Xdebug";
    #jvm_options "-Xrunjdwp:server=y,transport=dt_socket,address=840#{pno},suspend=n";

    ###threads number for request handler thread pool on jvm, default is 0. 
    ###check more details from 
    #jvm_workers 8;

    server {
        listen       8080;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

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

       location /java {
         content_handler_type 'java';
         content_handler_name 'com.bolingcavalry.simplehello.HelloHandler';
       }
       
#      location /groovy {
#          handler_type 'groovy';
#          handler_code ' 
#               import nginx.clojure.java.NginxJavaRingHandler;
#               import java.util.Map;
#               public class HelloGroovy implements NginxJavaRingHandler {
#                  public Object[] invoke(Map<String, Object> request){
#                     return [200, //http status 200
#                             ["Content-Type":"text/html"], //headers map
#                             "Hello, Groovy & Nginx!"]; //response body can be string, File or Array/Collection of them
#                  }
#               }
#          ';
#       }
#         
    }
}

啓動nginx

  • 啓動命令很簡單,在nginx-clojure-0.5.2目錄下執行./nginx
  • 如果啓動失敗了,請打開nginx-clojure-0.5.2/logs/error.log查看問題,例如我這裏遇到過端口占用導致啓動失敗:
2022/02/02 17:45:07 [emerg] 27703#0: bind() to 0.0.0.0:8080 failed (48: Address already in use)
2022/02/02 17:45:07 [emerg] 27703#0: bind() to 0.0.0.0:8080 failed (48: Address already in use)
2022/02/02 17:45:07 [emerg] 27703#0: bind() to 0.0.0.0:8080 failed (48: Address already in use)
2022/02/02 17:45:07 [emerg] 27703#0: bind() to 0.0.0.0:8080 failed (48: Address already in use)
2022/02/02 17:45:07 [emerg] 27703#0: bind() to 0.0.0.0:8080 failed (48: Address already in use)
2022/02/02 17:45:07 [emerg] 27703#0: still could not bind()

驗證

  • 打開postman驗證服務是否正常,請求地址是http://127.0.0.1:8080/java
  • 響應如下圖所示,符合預期,返回的就是咱們定製的HelloHandler的內容
    在這裏插入圖片描述
  • 至此,nginx-clojure的入門操作就完成了,雖然寥寥幾行代碼,但卻給java程序員打開了一扇窗:用咱們熟悉的技術去擴展nginx,打造更符合業務的web服務器,以最短鏈路完成web響應
  • 本篇只是nginx-clojure之旅的開端,先對nginx-clojure有個清晰的認識,接下來的文章咱們會深度探索它,讓它更好的服務於業務

源碼下載

名稱 鏈接 備註
項目主頁 https://github.com/zq2599/blog_demos 該項目在GitHub上的主頁
git倉庫地址(https) https://github.com/zq2599/blog_demos.git 該項目源碼的倉庫地址,https協議
git倉庫地址(ssh) [email protected]:zq2599/blog_demos.git 該項目源碼的倉庫地址,ssh協議
  • 這個git項目中有多個文件夾,本篇的源碼在nginx-clojure-tutorials文件夾下,如下圖紅框所示:
    在這裏插入圖片描述

歡迎關注博客園:程序員欣宸

學習路上,你不孤單,欣宸原創一路相伴...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章