0
点赞
收藏
分享

微信扫一扫

Spring Cloud Alibaba(15) - Spring Cloud Gateway

一、Spring Cloud Gateway是什么?

是Spring Cloud的第二代网关,未来会取代Zuul,基于Netty、Reactor以及WebFlux构建

优点:

  • 性能强劲,是第一代网关Zuul1.x的1.6倍

  • 功能强大,内置了很多实用功能,比如转发、监控、限流等

  • 设计优雅,易扩展

缺点:

  • 依赖Netty与Webflux,不是Servlet编程模型,有一定的适应成本

  • 不能在Servlet容器下工作,也不能构建成WAR包

  • 不支持Spring Boot 1.x

Spring Cloud Gateway核心概念

  • Route(路由)

    Spring Cloud Gateway的基础元素,可简单理解成一条转发的规则。包含:ID、目标URL、Predicate集合以及Filter集合

  • Predicate(谓词)

    即java.util.function.Predicate,Spring Cloud Gateway使用Predicate实现路由的匹配条件。

  • Filter(过滤器)

    修改请求以及响应

二、项目使用Spring Cloud Gateway

2.1 创建SpringBoot工程

使用Spring Initializr创建Spring Boot工程,并引入Spring Cloud Gateway

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>cn.xam.study</groupId>
        <artifactId>sca-study</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <groupId>cn.xam.study</groupId>
    <artifactId>gateway</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-nacos-discovery</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.2 写配置文件

server:
  port: 8040

spring:
  application:
    name: gateway
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
        # 指定namespace
        namespace: 62045631-10a2-41ea-837d-cf507cbdc8e0
        # 指定集群名称
        cluster-name: SZ
    gateway:
      discovery:
        locator:
          # 让gateway通过服务发现组件找到其他的微服务
          enabled: true
          lower-case-service-id: true

management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    health:
      show-details: always

logging:
  level:
    org.springframework.cloud.gateway: trace

举报

相关推荐

0 条评论