架构师进阶之九Consul+Openresty作为api gateway,


什么是API gateway

  • 确保客户端无法察觉应用程序是如何被拆分为多项微服务的。
  • 确保客户端不受服务实例的位置的影响。
  • 为每套客户端提供最优API。
  • 降低请求/往返次数。举例来说,API网关能够确保客户端在单次往返中就从多项服务中检索出数据。请求数量更少意味着运行负担更低且用户体验更好。API网关对于移动应用而言是必不可少的。
  • 将从客户端调用多项服务的逻辑转换为从API网关处调用,从而简化整个客户端

实现方式

1. nginx-upsync-module

该模块可以使nginx动态同步service 配置,无需重启生效。可以配合着consul或者etcd一起使用

下面的例子就是使用的consul。

nginx-upsync-module - Nginx C module, sync upstreams from consul or others, dynamically modify backend-servers attribute(weight, max_fails,...), needn't reload nginx.

It may not always be convenient to modify configuration files and restart NGINX. For example, if you are experiencing large amounts of traffic and high load, restarting NGINX and reloading the configuration at that point further increases load on the system and can temporarily degrade performance.

The module can be more smoothly expansion and constriction, and will not influence the performance.

http {
    upstream test {
        upsync 127.0.0.1:8500/v1/kv/upstreams/test/ upsync_timeout=6m upsync_interval=500ms upsync_type=consul strong_dependency=off;
        upsync_dump_path /usr/local/nginx/conf/servers/servers_test.conf;

        include /usr/local/nginx/conf/servers/servers_test.conf;
    }

    upstream bar {
        server 127.0.0.1:8090 weight=1 fail_timeout=10 max_fails=3;
    }

    server {
        listen 8080;

        location = /proxy_test {
            proxy_pass http://test;
        }

        location = /bar {
            proxy_pass http://bar;
        }

        location = /upstream_show {
            upstream_show;
        }

    }
}

2. OpenResty

一种整合了Nginx和lua的框架

OpenResty is a full-fledged web platform by integrating the standard Nginx core, LuaJIT, many carefully written Lua libraries, lots of high quality 3rd-party Nginx modules, and most of their external dependencies. It is designed to help developers easily build scalable web applications, web services, and dynamic web gateways

openresty包含了nginx核心以及上面的nginx-upsync-module模块

3. OpenResty单点故障

利用keepalived实现failover

 

4.Consul 简单介绍

  • 服务注册

   可以通过api注册,也可以通过json文件放置在特定目录下注册服务,代码如下:

{
    "service":{
        "name":"web",
        "tags":[
            "rails"
        ],
        "port":80,
        "check":{
            "name":"ping",
            "script":"curl -s localhost:80",
            "interval":"3s"
        }
    }
}
  • 服务发现

服务发现通过DNS或者http api可以查询域名下的服务 

5.nginx性能原理

 

 

 

相关内容

    暂无相关文章