群晖、NAS、PVE、Java后端、算法、微服务

每一个热爱技术的人都值得敬畏

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

Spring Cloud(Finchley版本)系列教程(五) 服务网关(Zuul) 一、Zuul简介 Zuu […]

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>

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

image-20240320143408376

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

image-20240320143438028

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

五、服务过滤

zuul不仅只是路由,并且还能过滤,做一些安全验证。继续改造工程,增加一个自定义的HepZuulFilter。

package cc.huerpu.eurekaserver.config;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class HepZuulFilter extends ZuulFilter {

    private static Logger log = LoggerFactory.getLogger(HepZuulFilter.class);
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        Object accessToken = request.getParameter("token");
        if(accessToken == null) {
            log.warn("hep zuul caller token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("hep zuul caller token is empty");
            }catch (Exception e){}

            return null;
        }
        log.info("ok");
        return null;
    }
}

filterType返回一个字符串代表过滤器的类型,在zuul中定义了四种不同生命周期的过滤器类型,pre表示路由之前。
这时访问:http://localhost:8011/hep-a/getUserById 网页显示:

image-20240320153518872

访问:http://localhost:8011/hep-a/getUserById?token=PDIJPEIJ2308740HFE874Y69T43HHF77G36F6GF446FOQ83 网页正常显示

image-20240320153739806

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