zoukankan      html  css  js  c++  java
  • spring cloud微服务快速教程之(十) gateway 服务网关

    0、前言

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

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

      性能上,自然是异步非阻塞的gateway胜出;

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

      实际项目中建议选择gateway;

    1、集成gateway

    1-1、添加依赖

      新建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-2、添加配置

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

    Path=/api/user/**  相当于该微服务前缀 

    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-3、运行测试

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

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

  • 相关阅读:
    Java Learning (201108025)
    Java Learning (20110808)
    Negative numbers and binary representation
    “this” pointer
    NullPointerException
    Special Swiss Education
    Java Learning (20110802)
    More about Swiss keyboard
    About memory leak
    Application Verifier
  • 原文地址:https://www.cnblogs.com/yanghj/p/12353280.html
Copyright © 2011-2022 走看看