zl程序教程

您现在的位置是:首页 >  后端

当前栏目

spring-cloud-zuul

2023-09-11 14:21:08 时间

用途

  Zuul可能有点过时了,首先我们要先搞清楚zuul是干嘛的。Zuul这个名词来源于星际之剑2中的祖尔族,它在spring cloud中主要提供以下功能:

  1. 认证
  2. 压力测试
  3. 金丝雀测试Canary Testing
  4. 服务漂移Migration
  5. 动态路由
  6. 服务降级Load Shedding
  7. 静态资源渲染
  8. 主动流量管理Active traffic management

搭建过程

  首先是配好maven:

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

  然后是简单的写个应用类和main函数:

package net.cloudsun.zuul;

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

/**
 * 10/12/2022 2:02 PM 创建
 *
 * @author 花书粉丝
 */
@SpringBootApplication
@EnableZuulProxy
public class ZuulApplication {


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

  配置类:

zuul:
  routes:
    users:
      path: /token/**
      url: http://localhost:8080/token
server:
  port: 80

  然后相关的服务全部启动一下:
在这里插入图片描述
  再访问浏览器测试下:
在这里插入图片描述
  测试成功。

Service Id

  前面的例子是写完整的URL,这在实际的微服务场景中是不常见的。因为现在微服务都是在虚拟机上,IP地址不固定,所以都是用eureka等注册中心去寻找服务的真实IP与端口,那这种怎么配置呢?首先写一个bootstrap.yml:

spring:
  application:
    name: zuul
eureka:
  client:
    fetch-registry: true
    register-with-eureka: true
    service-url:
      defaultZone: http://eureka-1:8761/eureka/
ribbon:
  eureka:
    enabled: true

  然后再修改下配置文件:

zuul:
  routes:
    users:
      path: /user/**
      service-id: server
      prefix: /token
server:
  port: 80

  这个配置文件表明/user开头的所有请求都会转发到server这台服务器。举两个例子:

在这里插入图片描述
在这里插入图片描述
  如此,就将固定URL改成了从注册中心寻找协议+IP+端口拼接URL。