# Spring Cloud(Finchley版本)系列教程(五) 服务网关(Zuul)

# 一、Zuul简介

Zuul 是 Netflix OSS 中的一员,是一个基于 JVM 路由器服务端的负载均衡器。提供路由、监控、弹性、安全等方面的服务框架。Zuul 能够与 Eureka、Ribbon、Hystrix 等组件配合使用。

zuul核心功能是过滤器、路由、异常处理,通过过滤器还能扩展出其他功能:

1)动态路由、2)请求监控、3)认证鉴权、4)压力测试、5)灰度发布

Zuul的主要功能是路由转发和过滤器。路由功能是微服务的一部分,比如/api/user转发到到user服务,/api/shop转发到到shop服务。zuul默认和Ribbon结合实现了负载均衡的功能。

# 二、创建Zuul工程

复制eurekaClient工程,修改名称为hepServiceZuul。

<artifactId>hepServiceZuul</artifactId>
<name>hepServiceZuul</name>
<description>hepServiceZuul</description>

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

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
13

# 三、启用并配置Zuul

启动类HepServiceZuulApplication加上注解@EnableZuulProxy,开启zuul的功能

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

@SpringBootApplication
@EnableDiscoveryClient
@EnableZuulProxy
public class HepServiceZuulApplication {

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

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

在application.yml上增加/hep-a/**/hep-b/**

zuul:
  routes:
    hep-a:
      path: /hep-a/**
      serviceId: hepServiceRibbonHystrix
    hep-b:
      path: /hep-b/**
      serviceId: hepServiceOpenFeignHystrix
1
2
3
4
5
6
7
8

application.yml文件内容如下

server:
  port: 8011 # 端口号

spring:
  application:
    name: hepServiceZuul # Eureka名称


zuul:
  routes:
    hep-a:
      path: /hep-a/**
      serviceId: hepServiceRibbonHystrix
    hep-b:
      path: /hep-b/**
      serviceId: hepServiceOpenFeignHystrix


eureka:
  instance:
    prefer-ip-address: false
    hostname: hepServiceZuul
  client:
    healthcheck:
      enabled: true
    fetch-registry: true
    register-with-eureka: true
    service-url:
      defaultZone: http://eureka:eurekapwd@www.huerpu.cc:1678/eureka/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

指定服务注册中心的地址为http://eureka:eurekapwd@www.huerpu.cc:1678/eureka/,服务的端口为8011,服务名为hepServiceZuul;以/hep-a/ 开头的请求都转发给hepServiceRibbonHystrix服务;以/hep-b/开头的请求都转发给hepServiceOpenFeignHystrix服务;

win11的host文件增加了下面三个

127.0.0.1   hepServiceZuul
127.0.0.1   hepServiceRibbonHystrix
127.0.0.1   hepServiceOpenFeignHystrix
1
2
3

# 四、验证Zuul

打开浏览器访问http://localhost:8011/hep-a/getUserById

image-20240320143408376

访问http://localhost:8011/hep-b/getUserById

image-20240320143438028

这说明zuul起到了路由的作用。

参考文章https://forezp.blog.csdn.net/article/details/81041012

最近更新: 12/3/2024
勤奋的凯尔森同学   |  
Spring Cloud(Finchley版本)系列教程(五) 服务网关(Zuul)