spring cloud微服务快速教程之(十) gateway 服务网关

0、前言

  gateway是spring的二代网关, 做为Netflix Zuul的替代者,是异步非阻塞网关 ,ZUUL2也是异步非阻塞的,但未归入spring cloud整合计划web

  基于WebFlux ,与spring-boot-starter-web冲突,要排除该依赖;ZUUL1是阻塞io的API Gateway;spring

  性能上,天然是异步非阻塞的gateway胜出,不过实际项目中,通常系统比较少达到性能极限,区别不大;api

  WebFlux 我的认为很鸡肋,没啥实际价值,ZUUL更简单方便;app

  如何取舍,见仁见智了,不要盲目认为gateway比ZUUL1好,适合项目才是最好的异步

一、集成gateway

1-一、添加依赖spring-boot

  新建gateway模块,添加依赖,注意要排除spring-boot-starter-web依赖,不能添加该依赖微服务

        <!-- 集成nacos -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2.0.1.RELEASE</version>
        </dependency>

        <!-- 集成gateway -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

 

1-二、添加配置性能

uri: lb://注册中心的微服务名称测试

Path=/api/user/**  至关于该微服务前缀 spa

StripPrefix=2   表示跳过前缀节数,上面前缀/api/user/是两节,说以是2,若是/api/则跳过1节

以上几个经常使用属性是通俗的解释,具体各个属性及其详细用法请参考官方文档

 

server:
  port: 8770
spring:
  application:
    name: gateway
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

    gateway:
      discovery:
        locator:
          enabled: false
          #开启小写验证,默认feign根据服务名查找都是用的全大写
          lowerCaseServiceId: true
      routes:
        - id: nacos-user
          uri: lb://nacos-user
          predicates:
            - Path=/api/user/**
          filters:
            - StripPrefix=2
        - id: nacos-order
          uri: lb://nacos-order
          predicates:
            - Path=/api/order/**
          filters:
            - StripPrefix=2

 

1-三、运行测试

  以上便可,运行项目,能够看到路由已经正常转发了

 

 

gateway简单的路由转发功能就这样完成了,其余的诸多路由过滤、匹配、限流等功能之后再探讨

相关文章
相关标签/搜索