nginx有路由API吗?

时间:2016-02-12 18:45:24

标签: nginx routing

我试图看看nginx(OSS,非商用)是否不仅可以用作负载均衡器,还可以用作网络路由器/交换机,如果我需要关闭我的应用程序并将流量重定向到CDN /静态页面等

我希望找到一个可以允许我动态配置路由规则的REST API,但是唉,我什么都没看到。

nginx是否提供开箱即用的功能?或者我可以将它配对吗?这将是一个平衡的Java应用程序,我看到有一个nginx-clojure模块。所以也许我可以通过Java(在nginx服务器上运行)以某种方式暴露一个REST端点......想法?

2 个答案:

答案 0 :(得分:2)

如果您使用nginx-clojure进行此类工作,则需要

  • 用作路由器的java / clojure重写处理程序
  • 充当路由器API端点的java / clojure内容处理程序
  • 共享地图,用于在nginx工作进程之间共享状态/规则(如果nginx工作进程的数量> 1,则需要这样做)

e.g。

在nginx.conf

## InitHandler is used to initialize shared map
jvm_init_handler_name my.InitHandler;

upstream myApp {
  .....
}

## requests will be redirected to upstream staticBackend when my app is down
upstream staticBackend {
 ....
}

server {

....

## share state/rules among nginx worker processes
shared_map routerRules tinymap?space=32k&entries=256;

## $mybackend will be changed by rewrite handler MyRouter
set $mybackend "";

location / {
  rewrite_handler_type java;
  rewrite_handler_name my.MyRouter;

  proxy_pass http://$mybackend;
}

location /restapi {
  content_handler_type java;
  content_handler_name my.MyRouterApi;
}

}

在InitHandler.java

public class InitHandler implements NginxJavaRingHandler {
  public static NginxSharedHashMap<String, String> rules;

  public Object[] invoke(Map<String, String> fakeRequest) {
     rules = NginxSharedHashMap.build("routerRules");
  }
}

在MyRouter.java

public class MyRouter implements  NginxJavaRingHandler {
   public Object[] invoke(Map<String, String> req) {
       String backend = InitHandler.rules.get("mybackend");
       if (backend == null) {
            backend = "myApp"; 
        }
       ((NginxJavaRequest)req).setVariable("mybackend", backend);
       return nginx.clojure.java.Constants.PHASE_DONE;
   }
}

在MyRouterApi.java

public class MyRouterApi implements  NginxJavaRingHandler {
   public Object[] invoke(Map<String, String> req) {

       String backend = req.get(MiniConstants.QUERY_STRING);

       /*chek backend ...... */

       //update the entry whose key is "mybackend" in the shared map
       InitHandler.rules.put("mybackend", backend);

        return new Object[] {200, null, "OK"};
   }
}

可以从https://nginx-clojure.github.io/找到更多文档。

BTW embedding API将使用nginx-clojure进行开发/测试非常容易。

答案 1 :(得分:1)

There is no API out of the box. You have to write some endpoint-snippets and use variables in your upstream config.

Take a look at:

https://github.com/openresty/lua-nginx-module#readme

It's fairly simple.