跳转至

网关#

约 158 个字 2 行代码 预计阅读时间 3 分钟

网关的作用#

  • 反向代理
  • 鉴权
  • 流量控制
  • 熔断
  • 日志监控

Spring Cloud Gateway入门案例#

创建路由模块:

创建Spring Boot
选择gateway依赖

项目创建成功,pom.xml文件如下:

XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.luguosong</groupId>
    <artifactId>gateway-hello</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>gateway-hello</name>
    <description>gateway-hello</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>17</java.version>
        <spring-cloud.version>2023.0.2</spring-cloud.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

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

</project>

在spring boot配置文件中配置网关路由:

YAML
server:
  port: 8100
spring:
  application:
    name: gateway-hello
  cloud:
    gateway:
      routes:
        - id: gateway-hello
          uri: http://localhost:8101/
          predicates:
            - Path=/**

创建端口号为8101的测试目标模块。

通过 http://localhost:8101/hello 可以直接访问目标服务(实际开发中前端不会直接访问目标服务)

现在有了网关,可以通过网关访问目标服务:http://localhost:8100/hello

路由(Route)#

路由固定地址#

路由指定服务名#

断言(Predicate)#

过滤器(Filter)#

评论