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

发布于:2024-03-21 ⋅ 阅读:(54) ⋅ 点赞:(0)

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

为了更好的浏览体验,欢迎光顾勤奋的凯尔森同学个人博客http://www.huerpu.cc:7000

一、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>

三、启用并配置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);
    }

}

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

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

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/

指定服务注册中心的地址为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

四、验证Zuul

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

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

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

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

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

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

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到