SpringCloud 之 Hystrix 断路器聚合监控 [ Turbine ](四)

项目文件:下载 324KB,可以用于 对比文件 及 目录结构,提前 查看效果,上文传送地址:Zipkin 链路追踪

一、为什么用断路器。

我们知道,视图微服务是依赖于数据微服务的。那么当数据微服务不可用的时候,会怎么样呢?
当我们访问时会抛出异常,出现这个问题肯定是难以避免的,比如数据微服务所在的机房停电了。 但是这样的提示信息是非常不友好的,客户也看不懂这个是什么。为了解决这个问题,我们就会引入断路器的概念。
在这里插入图片描述

所谓的断路器,就是当被访问的微服务无法使用的时候,当前服务能够感知这个现象,并且提供一个备用的方案出来。
比如在这个例子里,数据微服务无法使用了,如果有了断路器,那么视图微服务就能够知道此事,并且展示给用户相关的信息。 而不会报错或者一直卡在那里。在这里插入图片描述

二、Hystrix 断路器的配置。

2.1 改造。

视图服务 linze-view-service-feign 需要进行改造。

2.2 pom.xml。

添加 spring-cloud-starter-netflix-hystrix 以支持断路器。

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

2.3 application.yml。

# 开启断路器
# server.port 就不设置了,因为要启动多个端口,如 8011、8012、8013 ...... 。

# Spring的配置
spring:
  application:
    # 视图微服务名称
    name: linze-view-service-feign
  zipkin:
    base-url: http://localhost:9411
  # 模板引擎配置
  profiles: default
  freemarker:
    template-loader-path: classpath:/templates/views/ftl/
    cache: false
    check-template-location: true
    content-type: text/html; charset=UTF-8
    expose-request-attributes: true
    expose-session-attributes: true
    request-context-attribute: request
    suffix: .ftl
# 注册到服务中心
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
# 开启断路器
feign:
  hystrix:
    enabled: true

2.4 创建 BugsClientFeignHystrix 实现类。

当数据服务不可用及宕机时,用于反馈信息。

package cn.lz.cloud.viewservicefeign.client.impl;

import cn.lz.cloud.publics.vo.Bugs;
import cn.lz.cloud.viewservicefeign.client.BugsClientFeign;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author NingZe
 * description:
 * path: LinZeCloud-cn.lz.cloud.viewservicefeign.client.impl-BugsClientFeignHystrix
 * date: 2019/11/21 0021 14:56
 * version: 02.06
 * To change this template use File | Settings | File Templates.
 */
@Component
public class BugsClientFeignHystrix implements BugsClientFeign {

    @Override
    public List<Bugs> listBugs() {
        return new ArrayList<>() {{
            add(new Bugs("500", "数据微服务不可用", "500", "500"));
        }};
    }

}

2.5 修改 BugsClientFeign。

注解由原来的
@FeignClient(value = “LINZE-DATA-SERVICE”)
修改为
@FeignClient(value = “LINZE-DATA-SERVICE”,fallback = BugsClientFeignHystrix.class)
这就表示,如果访问的 LINZE-DATA-SERVICE 不可用的话,就调用 BugsClientFeignHystrix来进行反馈信息。

package cn.lz.cloud.viewservicefeign.client;

import cn.lz.cloud.publics.vo.Bugs;
import cn.lz.cloud.viewservicefeign.client.impl.BugsClientFeignHystrix;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author NingZe
 * description:
 * path: LinZeCloud-cn.lz.cloud.viewservicefeign.client-BugsClientFeign
 * date: 2019/11/11 0011 11:27
 * version: 02.06
 * To change this template use File | Settings | File Templates.
 */
@FeignClient(value = "LINZE-DATA-SERVICE", fallback = BugsClientFeignHystrix.class)
public interface BugsClientFeign {

    @GetMapping("bugs")
    List<Bugs> listBugs();

}

2.6 通过网关访问,编辑 - 网关服务 application.yml。

因为网关默认熔断时间是1秒,大于1秒,就超时了,所以出现了504错误。
如果没有设置,该错误将在关闭数据服务时,访问 http://localhost:8026/api-view/bugs 出现。
在这里插入图片描述
所以我们要设置他的熔断时间。

server:
  port: 8026
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
spring:
  application:
    name: linze-zuul-service
  zipkin:
    base-url: http://localhost:9411
# 路由映射
zuul:
  routes:
    api-a:
      # 访问路径
      path: /api-data/**
      # 服务名
      serviceId: LINZE-DATA-SERVICE
    api-b:
      path: /api-view/**
      serviceId: LINZE-VIEW-SERVICE-FEIGN
  host:
    socket-timeout-millis: 60000
    connect-timeout-millis: 60000

ribbon:
  ReadTimeout: 120000 #请求处理的超时时间
  ConnectTimeout: 60000 #请求连接的超时时间

hystrix:
  command:
    c4i-store:
      execution:
        timeout:
          enabled: true
        isolation:
          thread:
            timeoutInMilliseconds: 120000
            ribbon:
              ReadTimeout: 120000
              ConnectTimeout: 60000

2.7 启动。

依次启动

EurekaServerApplication
DataServiceApplication8001、ViewServiceFeignApplication8011、ZuulServiceApplication
可以集群,但懒得启动啦。

数据服务 http://localhost:8026/api-view/bugs 可用时,如下图
在这里插入图片描述
现在我们关闭数据服务
数据服务 http://localhost:8026/api-view/bugs 不可用时,如下图

在这里插入图片描述

三、创建子工程 linze-turbine-service 断路器聚合监控微服务

断路器聚合监控微服务。

3.1 工程创建。

在这里插入图片描述

3.2 文件配置。

3.2.0 编辑 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>cn.lz</groupId>
        <artifactId>cloud</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <artifactId>turbine-service</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <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-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-turbine</artifactId>
        </dependency>
    </dependencies>

</project>

3.2.1 编辑 application.yml。

配置信息,主要是:
appConfig: product-view-service-feign
这就表示它会把所有微服务名称是product-view-service-feign 的实例信息都收集起来。

server:
  port: 8021
spring:
  application:
  	name: linze-turbine-service
turbine:
  aggregator:
    clusterConfig: default
  appConfig: linze-view-service-feign  ### 配置Eureka中的serviceId列表,表明监控哪些服务
  clusterNameExpression: new String("default")
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

3.2.2 编辑 TurbineServiceApplication 启动类。

@EnableHystrixDashboard 启用断路器监控 - 视图界面。
@EnableTurbine 启用断路器聚合监控。

package cn.lz.cloud.turbineservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.netflix.turbine.EnableTurbine;

@SpringBootApplication
@EnableHystrixDashboard
@EnableTurbine
public class TurbineServiceApplication {

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

}

3.2.3 编辑 - 视图服务 pom.xml。

添加 spring-boot-starter-actuator 应用监控,本文用于访问路径: /actuator/hystrix.stream。

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

3.2.4 编辑 - 视图服务 application.yml。

# 开启断路器
feign:
  hystrix:
    enabled: true
# 路径访问允许,这样才能访问 /actuator/hystrix.stream
management:
  endpoints:
    web:
      exposure:
        include: "*"
      cors:
        allowed-origins: "*"
        allowed-methods: "*"

3.2.5 编辑 - 视图服务 ViewServiceFeignApplication 启动类。

@EnableCircuitBreaker 启用信息共享给监控中心。

package cn.lz.cloud.viewservicefeign;

import brave.sampler.Sampler;
import cn.hutool.core.net.NetUtil;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
@EnableCircuitBreaker
public class ViewServiceFeignApplication {

    public static void main(String[] args) {
        // 因为要启动多个,例如 8111、8012、8013 ......
        // 所以采用自动切换端口,去启动,启动的时候我们等待第一个启动完成后,在启动第二个
        int port = 8011;
        for (int i = 1; i <= 9; i++) {
            port = Integer.parseInt(801 + "" + i);
            if (!NetUtil.isUsableLocalPort(port)) {
                System.err.printf("端口%d被占用了,无法正常启动,正在更换端口,请稍等片刻...... %n", port);
                if (port == 8019) {
                    System.exit(1);
                }
                continue;
            }
            break;
        }
        System.out.printf("端口%d,启动中...... %n", port);
        new SpringApplicationBuilder(ViewServiceFeignApplication.class).properties("server.port=" + port).run(args);
    }

    @Bean
    public Sampler defaultSampler() {
        return Sampler.ALWAYS_SAMPLE;
    }

}

3.2.6 创建 - 公共模块 AccessViewService 访问类。

在 linze-publics\util 下创建不断访问服务的类 AccessViewService,用于观察监测视图现象。

package cn.lz.cloud.publics.util;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.http.HttpUtil;

/**
 * Created by IntelliJ IDEA.
 *
 * @author NingZe
 * description:
 * path: cloud-cn.lz.cloud.publics.util-AccessViewService
 * date: 2019/11/21 0021 17:26
 * version: 02.06
 * To change this template use File | Settings | File Templates.
 */
public class AccessViewService {

    public static void main(String[] args) {
        while (true) {
            ThreadUtil.sleep(1000);
            try {
                String html = HttpUtil.get("http://localhost:8026/api-view/bugs");
                System.out.println("html length:" + html.length());
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }
        }
    }

}

3.2.7 启动,观测监控服务。

依次启动

EurekaServerApplication
DataServiceApplication8001、ViewServiceFeignApplication8011、ZuulServiceApplication
TurbineServiceApplication
可以集群,但懒得启动啦。

访问监控主页 http://localhost:8021/hystrix,如下图 。
在这里插入图片描述
在中间的框里输入 http://localhost:8021/turbine.stream,后点击 Monitor Stream,如下图,也可以点击 skip 直接跳转,如下下图。
在这里插入图片描述
然后我们可以看到无信息,因为我们还没有访问,所以没有监控信息,如下图。
在这里插入图片描述

现在我们直接运行 公共模块中的 AccessViewService 类来持续自动访问,从而更清晰的观测监控服务,当然也可以手动。

1. 数据服务可用时,如下图
在这里插入图片描述
再附加一张图,如下图
在这里插入图片描述
现在我们关闭数据服务
2. 数据服务不可用时,过一会就变成红色 100.0% 啦,如下图

在这里插入图片描述
再附加一张图,如下图
在这里插入图片描述

本文到此结束,2019.11.22,下一篇 [ 配置服务器 及 Bus消息总线 ] ,待续 。。。。。。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值