| 
                         在这个阶段,我们的政策部分非常简单。位置块本身标记为第16行,这意味着客户端无法直接向它发出请求。重新定义$  api_name变量以匹配API的名称,以便它在日志文件中正确显示。最后,请求被代理到API定义部分中指定的上游组,使用$ request_uri变量 -  其中包含原始请求URI,未经修改。 
选择广泛或者精确的API定义 
API定义有两种方法 - 广泛而精确。每种API最合适的方法取决于API的安全要求以及后端服务是否需要处理无效的URI。 
在warehouse_api_simple.conf中,我们通过在第3行和第8行定义URI前缀来使用Warehouse  API的广泛方法。这意味着以任一前缀开头的任何URI都代理到相应的后端服务。使用基于前缀的位置匹配,对以下URI的API请求都是有效的: 
    - /api/warehouse/inventory
 
    - /api/warehouse/inventory/
 
    - /api/warehouse/inventory/foo
 
    - /api/warehouse/inventoryfoo
 
    - /api/warehouse/inventoryfoo/bar/
 
 
如果唯一的考虑是将每个请求代理到正确的后端服务,则广泛的方法提供最快的处理和最紧凑的配置。另一方面,精确的方法使API网关能够通过显式定义每个可用API资源的URI路径来理解API的完整URI空间。采用精确的方法,Warehouse  API的以下配置使用精确匹配(=)和正则表达式(〜)的组合来定义每个URI。 
- location = /api/warehouse/inventory { # Complete inventory 
 -  set $upstream inventory_service; 
 -  rewrite ^ /_warehouse last; 
 - } 
 -   
 - location ~ ^/api/warehouse/inventory/shelf/[^/]*$ { # Shelf inventory 
 -  set $upstream inventory_service; 
 -  rewrite ^ /_warehouse last; 
 - } 
 -   
 - location ~ ^/api/warehouse/inventory/shelf/[^/]*/box/[^/]*$ { # Box on shelf 
 -  set $upstream inventory_service; 
 -  rewrite ^ /_warehouse last; 
 - } 
 -   
 - location ~ ^/api/warehouse/pricing/[^/]*$ { # Price for specific item 
 -  set $upstream pricing_service; 
 -  rewrite ^ /_warehouse last; 
 - } 
 
  
此配置更详细,但更准确地描述了后端服务实现的资源。这具有保护后端服务免于格式错误的客户端请求的优点,代价是正常表达式匹配的一些小额外开销。有了这个配置,NGINX  Plus接受一些URI并拒绝其他URI无效: 
 
使用精确的API定义,现有的API文档格式可以驱动API网关的配置。可以从OpenAPI规范(以前称为Swagger)自动化NGINX Plus  API定义。此博客文章的Gists中提供了用于此目的的示例脚本。 
重写客户请求 
随着API的发展,有时会发生需要更新客户端的重大更改。一个这样的示例是重命名或移动API资源。与Web浏览器不同,API网关无法向其客户端发送命名新位置的重定向(代码301)。幸运的是,当修改API客户端不切实际时,我们可以动态地重写客户端请求。 
在下面的示例中,我们可以在第3行看到定价服务以前是作为库存服务的一部分实现的:rewrite指令将对旧定价资源的请求转换为新的定价服务。 
- # Rewrite rules 
 - # 
 - rewrite ^/api/warehouse/inventory/item/price/(.*) /api/warehouse/pricing/$1; 
 -   
 - # API definition 
 - # 
 - location /api/warehouse/inventory { 
 -  set $upstream inventory_service; 
 -  rewrite ^(.*)$ /_warehouse$1 last; 
 - } 
 -   
 - location /api/warehouse/pricing { 
 -  set $upstream pricing_service; 
 -  rewrite ^(.*) /_warehouse$1 last; 
 - } 
 -   
 - # Policy section 
 - # 
 - location /_warehouse { 
 -  internal; 
 -  set $api_name "Warehouse"; 
 -   
 -  # Policy configuration here (authentication, rate limiting, logging, more...) 
 -   
 -  rewrite ^/_warehouse/(.*)$ /$1 break; # Remove /_warehouse prefix 
 -  proxy_pass http://$upstream; # Proxy the rewritten URI 
 - } 
 
  
                        (编辑:泰州站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |