Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Spring Cloud教程 - Zuul网关入门 #7

Open
TFdream opened this issue Jul 17, 2020 · 0 comments
Open

Spring Cloud教程 - Zuul网关入门 #7

TFdream opened this issue Jul 17, 2020 · 0 comments

Comments

@TFdream
Copy link
Owner

TFdream commented Jul 17, 2020

Spring Cloud Zuul 是Spring Cloud Netflix 子项目的核心组件之一,可以作为微服务架构中的API网关使用,支持动态路由与过滤功能,本文将对其用法进行详细介绍。

Zuul简介

摘一段 Zuul 官网上的简介:

Zuul is an L7 application gateway that provides capabilities for dynamic routing, monitoring, resiliency, security, and more. Please view the wiki for usage, information, HOWTO, etc https://github.com/Netflix/zuul/wiki

API网关为微服务架构中的服务提供了统一的访问入口,客户端通过API网关访问相关服务。API网关的定义类似于设计模式中的门面模式,它相当于整个微服务架构中的门面,所有客户端的访问都通过它来进行路由及过滤。它实现了请求路由、负载均衡、校验过滤、服务容错、服务聚合等功能。

本篇将创建3个服务:

  • zuul-proxy:zuul-proxy模块来演示zuul的常用功能;
  • user-service:user-service模块来模拟用户服务;
  • product-service:product-service模块来模拟商品服务;

本篇中Spring Boot版本为 2.2.4.RELEASE,Spring Cloud版本为Hoxton.SR5。

创建zuul-proxy模块

在pom.xml中添加相关依赖:

    <properties>
        <spring-cloud.version>Hoxton.SR5</spring-cloud.version>
        <spring-boot.version>2.2.4.RELEASE</spring-boot.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <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>

    <dependencies>
        <!-- 引入 SpringMVC 相关依赖,并实现对其的自动配置 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>
    </dependencies>

在application.yml中进行配置:

server:
  port: 8801
spring:
  application:
    name: zuul-proxy
eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:8001/eureka/

在启动类上添加@EnableZuulProxy注解来启用Zuul的API网关功能:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

/**
 * @author Ricky Fung
 */
@EnableZuulProxy
@EnableDiscoveryClient
@SpringBootApplication
public class ZuulProxyApplication {

    public static void main(String[] args) {
        SpringApplication.run(ZuulProxyApplication.class, args);
    }
}

创建user-service模块

在pom.xml中添加相关依赖:

        <!-- 引入 SpringMVC 相关依赖,并实现对其的自动配置 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

在application.yml中进行配置:

# 服务端口号
server:
  port: 8081

# 服务名称
spring:
  application:
    name: user-service

eureka:
  instance:
    prefer-ip-address: true
  client:
    register-with-eureka: true # 注册到 Eureka-Server,默认为 true
    fetch-registry: true # 从 Eureka-Server 获取注册表,默认为 true
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka/ # Eureka-Server 地址

在启动类上添加@EnableDiscoveryClient注解开启服务注册/发现功能:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * @author Ricky Fung
 */
@EnableDiscoveryClient
@SpringBootApplication
public class UserApplication {

    public static void main(String[] args) {
        SpringApplication.run(UserApplication.class, args);
    }
}

增加一个测试用的Controller:

/**
 * @author Ricky Fung
 */
@RestController
@RequestMapping("/api")
public class UserApiController {

    @Value("${server.port:}")
    private Integer serverPort;

    @Value("${spring.application.name:}")
    private String applicationName;

    @GetMapping("/echo/{message}")
    public String echo(@PathVariable("message") String message) {
        return String.format("[%s : %s] hello %s", applicationName, serverPort, message);
    }
}

创建product-service模块

跟创建product-service模块 大同小异,这里就不赘述了。

Zuul常用功能演示

启动相关服务

这里我们通过启动eureka-server,两个user-service,product-service和zuul-proxy来演示Zuul的常用功能。

服务启动后打开 http://localhost:8761/ 显示如下:
image

配置路由规则

我们可以通过修改application.yml中的配置来配置路由规则,这里我们将匹配 /userService/** 的请求路由到user-service服务上去,匹配/productService/** 的请求路由到product-service上去,如下:

zuul:
  routes: #给服务配置路由
    user-service:
      path: /userService/**
    product-service:
      path: /productService/**

验证一下:

默认路由规则

Zuul和Eureka结合使用,可以实现路由的自动配置,自动配置的路由以服务名称为匹配路径,相当于如下配置:

zuul:
  routes: #给服务配置路由
    user-service:
      path: /user-service/**
    product-service:
      path: /product-service/**

验证一下:

如果不想使用默认的路由规则,可以添加以下配置来忽略默认路由配置:

zuul:
  ignored-services: user-service,product-service #关闭默认路由配置

负载均衡功能

多次调用 http://localhost:8080/api-gateway/user-service/api/echo/world 进行测试,可以发现运行在8081的user-service服务 多个实例交替出现。

配置访问前缀

我们可以通过以下配置来给网关路径添加前缀,此处添加了 api-gateway前缀,这样我们需要访问http://localhost:8080/api-gateway/user-service/api/echo/world 才能访问到user-service中的接口。

Header过滤及重定向添加Host

Zuul在请求路由时,默认会过滤掉一些敏感的头信息,以下配置可以防止路由时的Cookie及Authorization的丢失:

zuul:
  sensitive-headers: Cookie,Set-Cookie,Authorization #配置过滤敏感的请求头信息,设置为空就不会过滤

Zuul在请求路由时,不会设置最初的host头信息,以下配置可以解决:

zuul:
  add-host-header: true #设置为true重定向是会添加host请求头

查看路由信息

我们可以通过SpringBoot Actuator来查看Zuul中的路由信息。

在zuul-proxy模块 pom.xml中添加相关依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

修改application.yaml配置文件,开启查看路由的端点:

management:
  endpoints:
    web:
      exposure:
        include: 'routes'

通过访问http://localhost:8080/actuator/routes 查看简单路由信息:

通过访问http://localhost:8801/actuator/routes/details查看详细路由信息:

源码下载

spring-cloud-netflix-zuul:https://github.com/TFdream/spring-cloud-tutorials/tree/master/spring-cloud-netflix-zuul

相关资料

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant