搭建spring cloud gateway

在spring boot高版本中,网关使用gateway代替了zuul。这篇文章搭建一个gateway服务。

打开idea创建spring boot项目,打开pom.xml,需要的依赖如下图:

搭建spring cloud gateway_第1张图片

打开application.yaml文件,添加配置项:

搭建spring cloud gateway_第2张图片

 主要配置参数说明:

eureka.client.service-url.defaultZone:注册中心地址

spring.cloud.gateway.discovery.locator.enabled:让gateway可以发现微服务

routes下的参数说明:

id:就是此route的标记

uri:转发的地址,这里对应的是注册中心的微服务名

predicates:匹配的url路径,这里/userervice路径会转发到userservice微服务

filters:这个配置的是跳过几个前缀,这里是1,比如发送请求:

http://localhost:8011/userservice/user/getOrderInfo

其实际是寻址到userservice服务,找到/user/getOrderInfo接口,如果不配置StripPrefix=1,找的是/userservice/user/getOrderInfo接口。

启动类无需添加额外的注解,启动项目,查看注册中心是否有次gateway:

搭建spring cloud gateway_第3张图片

 截图表明注册中心已有该项目。使用postman发送请求,看是否能获取到数据:

搭建spring cloud gateway_第4张图片

 此gateway项目端口就是8011,通过gateway访问userservice接口,已获取到数据,表明gateway已正常搭建。

你可能感兴趣的:(java,spring,boot,spring)