网关
一切网络的流量都需要经过网关,api网关就是所有api请求都需要经过网关。
作用
对api进行一个统一的管理及处理,让业务更加专注于业务。
整合内部接口,统一开放入口:
对接不同客户:
天然的,我们可以在网关层就处理一些非业务强关联的事务,主要就涉及认证,安全,日志,流控,接口聚合,熔断处理等一系列服务能力。
Kong
kong就是一个基于nginx强力的http接入服务器,使用lua进行插件式高扩展能力,高性能的一个API网关。社区版通过插件方式提供了如下的能力,并可以通过lua编写插件的方式进行扩展:
安装
百闻不如一见,适用的情况下,我们就用最简便的方式,docker容器进行安装,快速高效,
在一个docker环境电脑中就行安装,步骤:
1.新建docker-compose.yml:内容下
version: '2.2' services: kong-database: image: postgres:9.4-alpine container_name: kong-database environment: - POSTGRES_USER=kong - POSTGRES_DB=kong healthcheck: test: "pg_isready -U kong && psql -d kong -U kong -c \"SELECT 1=1\"" interval: 10s timeout: 5s retries: 5 kong-migration: image: kong:${KONG_VERSION} container_name: kong-migration depends_on: kong-database: condition: service_healthy environment: - KONG_DATABASE=postgres - KONG_PG_HOST=kong-database command: sh -c "kong migrations up && touch migrations_run && sleep 30" healthcheck: test: "if [[ -f migrations_run ]] ; then exit 0; else exit 1; fi" interval: 10s timeout: 5s retries: 5 kong: image: kong:${KONG_VERSION} container_name: kong depends_on: kong-migration: condition: service_healthy healthcheck: test: "kong health" interval: 10s timeout: 5s retries: 5 environment: - KONG_DATABASE=postgres - KONG_PG_HOST=kong-database - KONG_ADMIN_LISTEN=0.0.0.0:8001 ports: - 8001:8001 - 8000:8000 kong-dashboard: image: pgbi/kong-dashboard container_name: kong-dashboard ports: - 8080:8080 depends_on: kong: condition: service_healthy entrypoint: ./docker/entrypoint.sh start --kong-url http://kong:8001
2.启动
KONG_VERSION=0.11-alpine docker-compose -f docker-compose.yml up
3.分析
在这里我们没有进行集群,一共启动三个服务,kong的数据库,kong网关,还有一个kong的管理应用,可以直观的提供web界面浏览kong网关相关信息。我们来看看提供出来的相关参数。
端口
kong:8000业务端口(所有api进此端口),8001管理端口(kong提供了restful管理接口,可对api,插件进行各种管理操作,如新增接口,新增用户等)。
kong的数据库可以使用postgres,也可以使用cassandra。