在上一章节中,我们做了网关的日志请求及全局异常,本章节我们将会介绍限流及断路。
对于很多同学来说,限流跟断路应该都是经常遇见的,但是有很多新同学并不知道,这里先介绍一下限流跟断路。
限流:限制流量,举个例子,我提供了一个接口出去,限定一秒内访问的次数只能是100次,这就是限流。本文采用谷歌的RateLimiter来实现
断路:断路也叫断路器,当一个请求一直在请求中,超过一定时间后,就会触发断路器,直接给请求返回一个异常,告知例如请求超时之类的提示。本文的断路器采用hystrix来实现,断路器面板采用dashboard
整体的项目结构如下:新增了两个类,断路器拦截,断路器配置类,限流器
项目结构图
接下里我们直接开干,首先是pom文件引入,增加以下包
<!-- 断路器 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!-- 断路器面板 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
新增断路器类FallbackFilter
/**
* All rights Reserved, Designed By OprCalf
* Copyright: Copyright(C) 2016-2020
* Company LengYin Ltd.
*/
package com.platform.gateway.common.filter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import com.platform.gateway.common.utils.MsgUtils;
/**
* @projectName: platform-gateway-demo
* @package: com.platform.gateway.common.filters
* @className: FallbackFilter.java
* @description: 路由断路器
* @