Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Spring Cloud 入门教程8、服务网关Zuul+Hystrix:断路处理与监控

Spring Cloud 入门教程8、服务网关Zuul+Hystrix:断路处理与监控

作者头像
KenTalk
发布于 2018-09-11 03:31:52
发布于 2018-09-11 03:31:52
6.3K00
代码可运行
举报
文章被收录于专栏:Ken的杂谈Ken的杂谈
运行总次数:0
代码可运行

一、前言

1、本篇主要内容

  • 通过实现FallbackProvider进行Zuul网关路由断路处理
  • Zuul+Hystrix路由断路监控配置与说明

2、本篇环境信息

框架

版本

Spring Boot

2.0.0.RELEASE

Spring Cloud

Finchley.RELEASE

Zuul

1.3.1

JDK

1.8.x

3、准备工作

参考上一篇:https://cloud.tencent.com/developer/article/1333841

基于源码:https://github.com/ken-io/springcloud-course/tree/master/chapter-07

  • 准备Eureka Server、服务提供者

启动Eureka Server: http://localhost:8800

启动Test Service:http://localhost:8602,http://localhost:8603

二、服务网关Zuul:服务断路处理

Zuul作为服务网关为了保证自己不被服务拖垮,本身已经集成了Hystrix对路由转发进行隔离。

为了方便开发人员对服务短路进行自定义处理,

Zuul 提供了 ZuulFallbackProvider 接口,开发人员可以通过实现该接口来完成自定义Hystrix Fallback

Spring Cloud Zuul 提供了 FallbackProvider替代了ZuulFallbackProvider接口。因此我们实现FallbackProvider即可

基于上一篇中zuul项目的源码进行修改即可:https://github.com/ken-io/springcloud-course/tree/master/chapter-07/zuul

1、实现FallbackProvider

在src\main\java\io\ken\springcloud\zuul创建package:provider

然后创建Filter类:ApiFallbackProvider.java

实现FallbackProvider并标记为@Component

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package io.ken.springcloud.zuul.provider;

import com.netflix.hystrix.exception.HystrixTimeoutException;
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 java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;

@Component
public class ApiFallbackProvider implements FallbackProvider {

    private Logger logger = Logger.getLogger(ApiFallbackProvider.class.toString());

    @Override
    public String getRoute() {
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        logger.warning(String.format("route:%s,exceptionType:%s,stackTrace:%s", route, cause.getClass().getName(), cause.getStackTrace()));
        String message = "";
        if (cause instanceof HystrixTimeoutException) {
            message = "Timeout";
        } else {
            message = "Service exception";
        }
        return fallbackResponse(message);
    }

    public ClientHttpResponse fallbackResponse(String message) {

        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return 200;
            }

            @Override
            public String getStatusText() throws IOException {
                return "OK";
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                String bodyText = String.format("{\"code\": 999,\"message\": \"Service unavailable:%s\"}", message);
                return new ByteArrayInputStream(bodyText.getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };

    }

}
  • FallbackProvider 成员说明

说明

getRoute()

该Provider应用的Route ID,例如:testservice,如果设置为 * ,那就对所有路由生效

fallbackResponse(String route, Throwable cause)

快速回退失败/响应,即处理异常并返回对应输出/响应内容。route:发生异常的RouteID,cause:触发快速回退/失败的异常/错误

ClientHttpResponse

Spring提供的HttpResponse接口。可以通过实现该接口自定义Http status、body、header

2、回退/失败响应测试

启动zuul项目,访问 http://localhost:8888/testservice?token=123

会得到正常响应内容:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
{
  "code": 0,
  "message": "hello",
  "content": null,
  "serviceName": "testservice",
  "host": "localhost:8602"
}

关掉testservice启动的实例。然后再访问 http://localhost:8888/testservice?token=123 ,就会看到

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
{
  "code": 999,
  "message": "Service unavailable:Timeout"
}

三、服务网关Zuul:服务断路监控/仪表盘

上一节咱们提到了,Zuul本身就集成了Hystrix,实际上Zuul的路由转发也是用到了Ribbon+Hystrix,也就意味着我们可以通过Hystrix Dashboard监控Zuul的工作情况

1、开启访问Hystri.stream入口

新建package:configuration,然后在此package下创建HystrixConfiguration.java

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package io.ken.springcloud.zuul.configuration;

import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HystrixConfiguration {

    @Bean(name = "hystrixRegistrationBean")
    public ServletRegistrationBean servletRegistrationBean() {
        ServletRegistrationBean registration = new ServletRegistrationBean(
                new HystrixMetricsStreamServlet(), "/hystrix.stream");
        registration.setName("hystrixServlet");
        registration.setLoadOnStartup(1);
        return registration;
    }

    @Bean(name = "hystrixForTurbineRegistrationBean")
    public ServletRegistrationBean servletTurbineRegistrationBean() {
        ServletRegistrationBean registration = new ServletRegistrationBean(
                new HystrixMetricsStreamServlet(), "/actuator/hystrix.stream");
        registration.setName("hystrixForTurbineServlet");
        registration.setLoadOnStartup(1);
        return registration;
    }
}

配置完成后重启启动zuul,访问 http://localhost:8888/hystrix.stream 或者

http://localhost:8888/actuator/hystrix.stream

就可以看到Hystrix流信息.(之所以配置两个入口,是为了满足turbine需要)

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
//截取片段
{"type":"HystrixCommand","name":"testservice","group":"RibbonCommand","currentTime":1532412948030,"isCircuitBreakerOpen":false,"errorPercentage":100,"errorCount":1,"requestCount":1}

这时候我们通过已有看板以链接方式查看Hystrix Dashboard,或者可以用Turbine来聚合Hystrix数据了。

当然,也可以在zuul项目中引入Hystrix Dashboard 进行监控。

2、引入Hystrix Dashboard

  • 修改pom.xml引入Hystrix Dashboard相关依赖
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package io.ken.springcloud.zuul;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@EnableHystrixDashboard
@EnableZuulProxy
@EnableEurekaClient
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

配置完成后重启启动zuul,访问 http://localhost:8888/hystrix ,就可以看到门户页

具体操作,不再赘述,参考本系列前面几篇Hystrix随笔即可

备注

  • 本篇代码示例

https://github.com/ken-io/springcloud-course/tree/master/chapter-08

  • 本篇参考

http://cloud.spring.io/spring-cloud-static/spring-cloud-netflix/2.0.0.RELEASE/single/spring-cloud-netflix.html#hystrix-fallbacks-for-routes

  • 相关阅读

https://cloud.tencent.com/developer/article/1333822

https://cloud.tencent.com/developer/article/1333825

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018/07/24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
Spring Cloud 入门教程5、服务容错监控:Hystrix Dashboard
上一篇我们介绍了Hystrix的基础使用,我们可以通过Hystrix做到依赖隔离和熔断等操作。但是只有工具的使用而没有监控,我们就无法在第一时间发现出现问题的依赖,也不能判断服务整体的健康状态/运行状态。所以我们还要做好相关的监控工作。
KenTalk
2018/09/11
1.4K0
Spring Cloud 入门教程5、服务容错监控:Hystrix Dashboard
Spring Cloud 入门教程7、服务网关(Zuul)
服务网关也就是API网关,服务网关可以作为服务的统一入口,提供身份校验、动态路由、负载均衡、安全管理、统计、监控、流量管理、灰度发布、压力测试等功能
KenTalk
2018/09/11
1.1K0
Spring Cloud 入门教程7、服务网关(Zuul)
Spring Cloud 入门教程6、Hystrix Dashboard监控数据聚合(Turbine)
Turbine是Netflix开源的将Server-Sent Event(SSE)的JSON数据流聚合成单个流的工具。我们可以通过Turbine将Hystrix生产的监控数据(JSON)合并到一个流中,方便我们对存在多个实例的应用进行监控。
KenTalk
2018/09/11
9360
Spring Cloud 入门教程6、Hystrix Dashboard监控数据聚合(Turbine)
Spring Cloud 入门教程6、Hystrix Dashboard监控数据聚合(Turbine)(转)
Turbine是Netflix开源的将Server-Sent Event(SSE)的JSON数据流聚合成单个流的工具。我们可以通过Turbine将Hystrix生产的监控数据(JSON)合并到一个流中,方便我们对存在多个实例的应用进行监控。
wuweixiang
2019/03/12
5590
Spring Cloud 入门教程6、Hystrix Dashboard监控数据聚合(Turbine)(转)
Spring Cloud 入门教程4、服务容错保护:断路器(Hystrix)
在分布式架构中,一个应用依赖多个服务是非常常见的,如果其中一个依赖由于延迟过高发生阻塞,调用该依赖服务的线程就会阻塞,如果相关业务的QPS较高,就可能产生大量阻塞,从而导致该应用/服务由于服务器资源被耗尽而拖垮。
KenTalk
2018/09/11
6630
Spring Cloud【Finchley】-17 使用Zuul为单个或全部微服务提供容错与回退功能
Spring Cloud【Finchley】-14 微服务网关Zuul的搭建与使用 # Step8. 网关功能-Hystrix监控测试中我们测试了Zuul默认集成了Hystrix的监控,但是没有提及容错。
小小工匠
2021/08/17
5580
Getway网关管理ZUUL
微服务架构体系中,通常一个业务系统会有很多的微服务,比如:OrderService、ProductService、UserService...,为了让调用更简单,一般会在这些服务前端再封装一层,类似下面这样:
Dream城堡
2018/09/10
9460
Getway网关管理ZUUL
SpringCloud-Zuul服务网关[容错Hystrix]
  zuul作为网关服务,用来分配调度其他服务的,那么难免就会出现调用的服务出现问题的请求,或者用户访问急剧增多的情况,那么此时我们的网关服务就应该具有容错能力,zuul本身也考虑到了这点,所以默认集成的有Hystrix。
用户4919348
2019/06/24
5840
SpringCloud-Zuul服务网关[容错Hystrix]
Spring Boot + Spring Cloud 构建微服务系统(七):API服务网关(Zuul)
前面我们通过Ribbon或Feign实现了微服务之间的调用和负载均衡,那我们的各种微服务又要如何提供给外部应用调用呢。
朝雨忆轻尘
2019/06/19
6850
Spring Boot + Spring Cloud 构建微服务系统(七):API服务网关(Zuul)
springCloud - 第12篇 - 服务监控 Hystrix 面板
前面有用过 Hystrix 熔断,在多服务运行时。可以通过 Hystrix 的监控面板来实时观察各个服务的运行健康、效率和请求量等。
微风-- 轻许--
2019/08/29
8940
springCloud - 第12篇 - 服务监控 Hystrix 面板
SpringCloud技术指南系列(十一)API网关之Zuul使用
API网关是一个更为智能的应用服务器,它的定义类似于面向对象设计模式中的Facade模式,它的存在就像是整个微服务架构系统的门面一样,所有的外部客户端访问都需要经过它来进行调度和过滤。它除了要实现请求路由、 负载均衡、 校验过滤等功能之外,还需要更多能力,比如与服务治理框架的结合、请求转发时的熔断机制、服务的聚合等一系列高级功能。
品茗IT
2019/09/12
5540
spring cloud 配置zuul实用
前面我们通过Ribbon或Feign实现了微服务之间的调用和负载均衡,那我们的各种微服务又要如何提供给外部应用调用呢。
爱撸猫的杰
2019/03/28
6060
spring cloud 配置zuul实用
SpringCloud Zuul2.X网关实现服务熔断降级(复制即用)
版本: <properties> <spring-boot.version>2.1.9.RELEASE</spring-boot.version> <spring-cloud.version>Greenwich.SR4</spring-cloud.version> </properties> 所需依赖:   <properties> <spring-cloud.version>Greenwich.SR4</spring-cloud.version> <
Arebirth
2020/06/19
6530
SpringCloud入门系列之API网关
网管Zulul也是一个微服务客户端,所以入口类上也需要添加@EnableEurekaClient或@EnableDiscoveryClient
AI码真香
2022/09/13
5310
SpringCloud之Zuul网关[通俗易懂]
路由规则: 请求url带有 /api-a/ 的路由到 ribbon-ha 服务(spring.application.name) 请求url带有 /api-b/ 的路由到 ribbon-hi 服务 请求url带有 /api-c/ 的路由到 feign-ha 服务(feign_haha 别名)
全栈程序员站长
2022/09/22
4390
SpringCloud之Zuul网关[通俗易懂]
springcloud(十一):服务网关Zuul高级篇
时间过的很快,写springcloud(十):服务网关zuul初级篇还在半年前,现在已经是2018年了,我们继续探讨Zuul更高级的使用方式。 上篇文章主要介绍了Zuul网关使用模式,以及自动转发机制
纯洁的微笑
2018/04/18
1.4K0
springcloud(十一):服务网关Zuul高级篇
Spring Cloud 系列之服务网关 Zuul
  Zuul 包含了对请求的路由和过滤两个最主要的功能:其中路由功能负责将外部请求转发到具体的微服务实例上,是实现外部访问统一入口的基础而过滤器功能则负责对请求的处理过程进行干预,是实现请求校验、服务聚合等功能的基础。Zuul 和 Eureka 进行整合,将 Zuul 自身注册为 Eureka 服务治理下的应用,同时从 Eureka 中获得其他微服务的消息,也即以后的访问微服务都是通过 Zuul 跳转后获得。继 Zuul 1.x 之后奈菲公司想推出 Zuul 2.x 但因为开发人员意见不合迟迟未推出,Spring 官方无法等待就自己研发了 Gateway 替代了 Zuul。Spring Cloud F 版推荐使用 Zuul,之后推荐使用 Gateway。
Demo_Null
2020/11/11
1.1K0
Spring Cloud 系列之服务网关 Zuul
SpringCloud中Zuul网关原理及其配置,看它就够了!
Zuul是spring cloud中的微服务网关。网关:是一个网络整体系统中的前置门户入口。请求首先通过网关,进行路径的路由,定位到具体的服务节点上。
JAVA葵花宝典
2020/12/15
3.4K0
SpringCloud中Zuul网关原理及其配置,看它就够了!
Spring-Cloud-Netflix-Zuul网关
配置完成后,再访问地址http://localhost:8003/goods/getGoods.do
JokerDJ
2023/11/27
2810
Spring-Cloud-Netflix-Zuul网关
spring cloud 学习(6) - zuul 微服务网关
微服务架构体系中,通常一个业务系统会有很多的微服务,比如:OrderService、ProductService、UserService...,为了让调用更简单,一般会在这些服务前端再封装一层,类似下
菩提树下的杨过
2018/01/18
1.5K0
spring cloud 学习(6) - zuul 微服务网关
推荐阅读
相关推荐
Spring Cloud 入门教程5、服务容错监控:Hystrix Dashboard
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验