SpringCloud 的Zuul理論和使用Zuul構建微服務網關以及Zuul網關使用熔斷器

本篇博客主要講微服務網關,和Zuul相關理論知識以及怎麼樣使用Zuul實現網關。

微服務網關

爲什麼要使用微服務網關?

不同的微服務一般會有不同的網絡地址,而外部客戶端可能需要調用多個服務的接口才能完成一個業務需求,如果讓客戶端直接與各個微服務通信,會有以下問題:

1、客戶端會多次請求不同的微服務,增加了客戶端的複雜性。

2、存在跨域請求,在一定場景下處理相對複雜。

3、認證複雜,每個服務都需要獨立認證。

4、難以重構,隨着項目的迭代,可能需要重新劃分微服務。

5、某些微服務可能使用了防火牆或瀏覽器不友好協議,直接訪問會有一定的困難。

如圖:

在這裏插入圖片描述
爲了解決這些問題,需使用微服務網關。微服務網關是介於客戶端和服務器端之間的中間層,所有的外部請求都會先經過微服務網關,如圖:

在這裏插入圖片描述

微服務網關封裝了應用程序的內部結構,客戶端只跟網關交互,無需直接調用特定微服務的接口,其優點:

1、易於監控:可在微服務網關收集監控數據並將其推送到外部系統進行分析。

2、易於認證:可在微服務網關上進行認證,在將請求轉發到後端的微服務,無需在每個微服務中進行認證。

3、減少了客戶端和各個微服務之間的交互次數。

在微服務架構中,需要幾個基礎的服務治理組件,包括服務註冊與發現、服務消費、負載均衡、斷路器、智能路由、配置管理等,由這幾個基礎組件相互協作,共同組建了一個簡單的微服務系統。一個簡答的微服務系統如下圖:
在這裏插入圖片描述
注意:A服務和B服務是可以相互調用的,作圖的時候忘記了。並且配置服務也是註冊到服務註冊中心的。

在Spring Cloud微服務系統中,一種常見的負載均衡方式是,客戶端的請求首先經過負載均衡(zuul、Ngnix),再到達服務網關(zuul集羣),然後再到具體的服。,服務統一註冊到高可用的服務註冊中心集羣,服務的所有的配置文件由配置服務管理(下一篇文章講述),配置服務的配置文件放在git倉庫,方便開發人員隨時改配置。

以上理論來自 https://blog.csdn.net/fivehundredyearsago/article/details/80730119 感謝

Zuul

Zuul簡介

Zuul是Netflix開源的微服務網關,可以和Eureka、Ribbon、Hystrix等組件配合使用,Spring Cloud對Zuul進行了整合與增強,Zuul默認使用的HTTP客戶端是Apache HTTPClient,也可以使用RestClient或okhttp3.OkHttpClient。 Zuul的主要功能是路由轉發和過濾器。路由功能是微服務的一部分,比如/api/user轉發到到user服務,/api/shop轉發到到shop服務。zuul默認和Ribbon結合實現了負載均衡的功能。

Zuul的核心是一系列的過濾器,這些過濾器可以完成以下功能:

1、身份認證與安全:識別每個資源的驗證要求,並拒絕那些與要求不符的請求。

2、審查與監控:在邊緣位置追蹤有意義的數據和統計結果,從而帶來精確的生產視圖。

3、動態路由:動態地將請求路由到不同的後端集羣。

4、壓力測試:逐漸增加指向集羣的流量,以瞭解性能。

5、負載分配:爲每一種負載類型分配對應容量,並啓用超出限定值的請求。

6、靜態響應處理:在邊緣位置直接建立部分響應,從而避免其轉發到內部集羣。

7、多區域彈性:跨越AWS Region進行請求路由,旨在實現ELB(Elastic Load Balancing)使用的多樣化,以及讓系統的邊緣更貼近系統的使用者。

zuul有以下功能:

Authentication
Insights
Stress Testing
Canary Testing
Dynamic Routing
Service Migration
Load Shedding
Security
Static Response handling
Active/Active traffic management

使用Zuul構建微服務網關

本次操作還是在之前的博客項目上改進實現 https://blog.csdn.net/weixin_42236165/article/details/92842773 https://blog.csdn.net/weixin_42236165/article/details/93159034

1.首先再創建一個創建eureka-zuul項目

在這裏插入圖片描述
pom.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.szh</groupId>
    <artifactId>eureka-zuul</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>eureka-zuul</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <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>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <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>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.在啓動類EurekaZuulApplication加上註解@EnableZuulProxy,開啓zuul的功能:

package com.szh.eurekazuul;

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;


@EnableZuulProxy
@EnableDiscoveryClient
@SpringBootApplication
public class EurekaZuulApplication {

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

}

在這裏插入圖片描述
3.在配置文件application.yml加上以下的配置代碼:

路由轉發
zuul.routes.api-student.service-id=eureka-student轉發到到eureka-student服務,zuul.routes…api-grade.service-id=eureka-grade轉發到到eureka-grade服務

spring.application.name=eureka-zuul
server.port=8089
eureka.client.serviceUrl.defaultZone=http://localhost:8080/eureka/

zuul.routes.api-student.path=/student/**
zuul.routes.api-student.service-id=eureka-student

zuul.routes.api-grade.path=/grade/**
zuul.routes..api-grade.service-id=eureka-grade

首先指定服務註冊中心的地址爲http://localhost:8089/,服務的端口爲8089,服務名爲service-zuul;以/api-student/ 開頭的請求都轉發給eureka-student服務;以/api-grade/開頭的請求都轉發給eureka-grade服務;

4.測試(路由轉發)
依次啓動springcloud-eureka-server、springcloud-eureka-grade、spring-eureka-student,springcloud-eureka-zuul四個項目。

打開瀏覽器訪問:http://localhost:8089/student/grades ;瀏覽器顯示:

在這裏插入圖片描述

服務過濾

5.zuul不僅只是路由,並且還能過濾,做一些安全驗證。繼續改造工程;

增加一個MyZuulFilter類

package com.szh.eurekazuul.filter;

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

import javax.servlet.http.HttpServletRequest;

@Component
public class MyZuulFilter extends ZuulFilter{

    private Logger log = LoggerFactory.getLogger(MyZuulFilter.class);

    @Override
    public String filterType() {
        //路由之前要做的處理
        return "pre";
    }

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

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

    @Override
    public Object run() throws ZuulException {
        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("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            }catch (Exception e){}
            return null;
        }
        log.info("ok");
        return null;
    }
}

在這裏插入圖片描述
filterType:返回一個字符串代表過濾器的類型,在zuul中定義了四種不同生命週期的過濾器類型,具體如下:
pre:路由之前
routing:路由之時
post: 路由之後
error:發送錯誤調用
filterOrder:過濾的順序
shouldFilter:這裏可以寫邏輯判斷,是否要過濾,本文true,永遠過濾。
run:過濾器的具體邏輯。可用很複雜,包括查sql,nosql去判斷該請求到底有沒有權限訪問。

6.測試
關閉springcloud-eureka-zuul項目在打開

打開瀏覽器訪問:http://localhost:8089/student/grades ;瀏覽器顯示:
token is empty
在這裏插入圖片描述
訪問http://localhost:8089/student/grades?token=dfssf ; 顯示
在這裏插入圖片描述
成功!

然後用網關去嘗試上篇寫的熔斷器的時候會遇到一些問題

依次啓動完項目後
先訪問 http://localhost:8089/student/grades?token=dfssf

在這裏插入圖片描述
接下來我們手動停止springcloud-eureka-grade項目再次測試:
在瀏覽器中輸入:http://localhost:8089/student/grades?token=dfssf

在這裏插入圖片描述
報錯!

解決方法如下在service-zuul項目中的application.properties中加入代碼

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 6000
hystrix.command.default.execution.timeout.enabled: true
feign.hystrix.enabled: true
spring.cloud.loadbalancer.retry.enabled: true
ribbon.ReadTimeout: 6000
ribbon.ConnectTimeout: 6000

在依次啓動一遍項目測試
訪問 http://localhost:8089/student/grades?token=dfssf

在這裏插入圖片描述
接下來我們手動停止springcloud-eureka-grade項目再次測試:
在瀏覽器中輸入:http://localhost:8089/student/grades?token=dfssf

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章