用Zuul开发微服务网关

这三个依赖以及web一定要有

修改成这个,然后从同一配置中心获取api-gateway服务的配置

启动项目,确认能正常启动后,在API-gateway服务的启动类加上EnableZuulProxy注解,再次启动项目

现在我启动的服务有eureka(8761)、config(8088)、product(8080)、API-gateway(8060),没有这些服务的请看我之前的文章。
先通过直接访问product(8080)项目,看看product/list接口是否正常,如下所示,正常返回数据

现在通过API-gateway(8060)服务访问product服务的product/list接口,也能返回数据
完整路径:8060/product/product/list
即:API-gateway服务端口/对应的服务名称/实际的URL

如果不想直接显示对应服务名称,可以采用如下配置进行,例如product服务,我现在通过zuul访问时采用myProduct访问

通过myProduct方式访问成功

此外还有一种简洁的写法如下

查看所有路由的访问规则:application/routes


禁止某些路由被访问:
比如禁止访问product服务里面有个product/test接口地址

这个地址就被禁止访问了

上面的配置由于有别名所以要写两个地址,其实也可以用通配符的方式

如果product想要获得http请求的敏感信息如cookie等,还需要配置一下sensitiveHeaders,如下面的,留空即可

zuul的高可用
api-gateway的本质也是一个微服务,所以它的高可用和普通服务一样,都是部署多个服务节点,然后注册到Eureka Server,对内照样是通过Ribbon的负载均衡策略进行转发,对外就采用Nginx+Zuul的混搭,用Nginx去做集群的负载均衡、转发。
代码: https://github.com/hmilyos/springCloud-api-gateway.git base分支