SpringCloud Hystrix 实战

一、配置

1.引入jar包

单独使用hystrix ,不配合openFegin使用的话,单独使用hystrix,需要引入spring-cloud-starter-netflix-hystrix包。要使用的hystrix-dashboard 界面的话需要引入spring-boot-starter-actuator 包和spring-cloud-starter-netflix-hystrix-dashboard 包

  <!--不配合openfegin单独使用hystrix-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

        <!-- pom必须引入actuator,所有需要被监控的服务都要引入actuator-->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-actuator</artifactId>
       </dependency>
        <!-- 引入 hystrix-dashboard-->
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
       </dependency>

1.2 开启注解

要使用的 熔断讲解功能需要开启@EnableHystrix注解,要开启HystrixDashboard 监控功能
需要@EnableHystrixDashboard 注解

1.2.1 在ribbin 项目上使用hiystirxDashboard 的配置

配置HystrixDashboard 监控访问的 stream的监控流serverlet
/hystrix.stream

@SpringBootApplication
//开启Hystrix熔断,或者使用@EnableCircuitBreaker
@EnableHystrix
//开启HystrixDashboard
@EnableHystrixDashboard
public class AmasterReportServerApplication {

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

}



    @Bean
    public ServletRegistrationBean getServlet() {
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/hystrix.stream");
        registrationBean.setName("HystrixMetricsStreamServlet");
        return registrationBean;
    }


由于springcloud的版本不同,有些版本在访问界面的时候不配置ServletRegistrationBean 会在打开hystrixdash的访问页面,输入监控的hystrix.stream地址,在进入hystrixdash的监控界面会,监控解密那上会显示 Unable to connect to Command Metric Stream。有些版本不需要配置ServletRegistrationBean

1.2.2 项目上在openFegin项目上使用hystrixDashBoard

区别在ribbion 项目中使用hystrixDashBoard ,注册HystrixMetricsStreamServlet 的是使用注册servet的时候Mappring的url不同,使用openFegin项目的时候需要映射/actuator/hystrix.stream,要不然访问
http://localhost:9005/amaster-work-server/actuator/hystrix.stream 会后台会报404,访问不了

package com.zhang.buiness.amaster.workserver;

import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = {"com.zhang.buiness.amaster.workserver.client.fegin"})
@EnableHystrixDashboard
public class AmasterWorkServerApplication {

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


    @Bean
    public ServletRegistrationBean getServlet() {
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/actuator/hystrix.stream");
        registrationBean.setName("HystrixMetricsStreamServlet");
        return registrationBean;
    }

}

1.3 在调用方法上配置降级方法和熔断条件

@Slf4j
public class ReportServiceImpl {
    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand( commandProperties = {
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10")
    },fallbackMethod = "ribbionAloneUseFallback")
    public List<String> ribbionAloneUse(String clientMark, String path) {
        String url  = String.format("http://%s%s",clientMark,path);
        ResponseEntity<List> entity = restTemplate.getForEntity(url, List.class);
        return  entity.getBody();
    }


    //ribbionAloneUse方法降级服务
    public List<String> ribbionAloneUseFallback(String clientMark,String path,Throwable e){
        log.error(e.getMessage(),e);
        String url  = String.format("http://%s%s",clientMark,path);
        return Arrays.asList("触发降级"+url) ;
    }
}

注意:在配置熔断方法的时候,目标方法的降级方法,入参和返回值类型要相同。要不然在调用ribbionAloneUse 的时候会报

hystrix回调方法报错:fallback method wasn‘t found

hystrix降级的fallback方法需要与原方法有相同的返回类型和参数列表,fallback方法可以在参数列表后加一个Throwable类型参数用于接收异常信息

1.4 配置文件,配置dashboard的访问代理允许许可

amaster-report-server的服务配置文件

spring:
    application:
        name: amaster-report-server
    cloud:
        load-balancer:
#            ribbon:
#                eager-load:
#                    enabled: true # 开启饥饿加载,这里为配合注册中心使用,因此关闭掉懒加载
#                    clients: # 指定饥饿加载的服务名称
#                        - amaster-work-server   # 用户服务
#                        - amaster-config-env # 仓库服务
            #开启重试机制,默认是关闭的
            retry:
                enabled: true

amaster-work-server:
    ribbon:
        #请求连接的超时时间
        ConnectTimeout: 250
        #请求处理的超时时间
        ReadTimeout: 1000
        #对所有操作请求都进行重试,默认false,只有GET请求会重试;这是防止POST等对数据有影响的请求在重试后因为接口未做幂等性导致数据异常,影响较大
        OkToRetryOnAllOperations: true
        #切换实例的重试次数
        MaxAutoRetriesNextServer: 2
        #对当前实例的重试次数
        MaxAutoRetries: 1
        # 服务的实例地址列表
        listOfServers: localhost:9005,localhost:9015
        #给某个微服务配置负载均衡规则
        NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
#配置运训访问的监控地址列表
hystrix:
    dashboard:
        # "127.0.0.1"
        proxy-stream-allow-list: "**"
        
#hystrix:
#    dashboard:
#        # "127.0.0.1"
#        proxy-stream-allow-list: "localhost"


# 暴漏监控信息
management:
    endpoints:
        web:
            exposure:
                include: hystrix.stream
                
# 暴漏监控信息
#management:
#    endpoints:
#        web:
#            exposure:
#                include: "*"

如果不开启开启允许hystrixDashboard 的监控流代理地址,在通过监控首页输入监控服务地址hystrx.stream的访问监控地址的时候会报如下错

2024-04-27 00:00:29.767  WARN 15572 --- [nio-9007-exec-5] ashboardConfiguration$ProxyStreamServlet : Origin parameter: http://127.0.0.1:9007/amaster-report-server/actuator/hystrix is not in the allowed list of proxy host names.  If it should be allowed add it to hystrix.dashboard.proxyStreamAllowList.
2024-04-27 00:00:29.767  WARN 15572 --- [io-9007-exec-10] ashboardConfiguration$ProxyStreamServlet : Origin parameter: http://127.0.0.1:9007/amaster-report-server/actuator/hystrix is not in the allowed list of proxy host names.  If it should be allowed add it to hystrix.dashboard.proxyStreamAllowList.
2024-04-27 00:01:13.625  WARN 15572 --- [nio-9007-exec-8] ashboardConfiguration$ProxyStreamServlet : Origin parameter: http://127.0.0.1:9007/amaster-report-server/actuator/hystrix is not in the allowed list of proxy host names.  If it should be allowed add it to hystrix.dashboard.proxyStreamAllowList.
2024-04-27 00:01:13.625  WARN 15572 --- [nio-9007-exec-7] ashboardConfiguration$ProxyStreamServlet : Origin parameter: http://127.0.0.1:9007/amaster-report-server/actuator/hystrix is not in the allowed list of proxy host names.  If it should be allowed add it to hystrix.dashboard.proxyStreamAllowList.

1.5 测试

开启两个服务amaster-work-server 的两个服务
amaster-work-server 9015 和amaster-work-server 9005

在这里插入图片描述
在这里插入图片描述
amaster-report 服务未注册到中心,调用amaster-work-serve 的两个服务 通过ribbion的listOfServers 进行配置调用。可以看到两个服务被随机轮询调用;
当调用接口http://127.0.0.1:9007/amaster-report-server/env/get/report/ribbion/alone/use/v1 调用的时候会打印

2024-04-26 22:01:07.576  INFO 12804 --- [rtServiceImpl-1] c.netflix.loadbalancer.BaseLoadBalancer  : Client: amaster-work-server instantiated a LoadBalancer: DynamicServerListLoadBalancer:{NFLoadBalancer:name=amaster-work-server,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:null
2024-04-26 22:01:07.585  INFO 12804 --- [rtServiceImpl-1] c.n.l.DynamicServerListLoadBalancer      : Using serverListUpdater PollingServerListUpdater
2024-04-26 22:01:07.613  INFO 12804 --- [rtServiceImpl-1] c.n.l.DynamicServerListLoadBalancer      : DynamicServerListLoadBalancer for client amaster-work-server initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=amaster-work-server,current list of Servers=[localhost:9005, localhost:9015],Load balancer stats=Zone stats: {unknown=[Zone:unknown;	Instance count:2;	Active connections count: 0;	Circuit breaker tripped count: 0;	Active connections per server: 0.0;]
},Server stats: [[Server:localhost:9015;	Zone:UNKNOWN;	Total Requests:0;	Successive connection failure:0;	Total blackout seconds:0;	Last connection made:Thu Jan 01 08:00:00 CST 1970;	First connection made: Thu Jan 01 08:00:00 CST 1970;	Active Connections:0;	total failure count in last (1000) msecs:0;	average resp time:0.0;	90 percentile resp time:0.0;	95 percentile resp time:0.0;	min resp time:0.0;	max resp time:0.0;	stddev resp time:0.0]
, [Server:localhost:9005;	Zone:UNKNOWN;	Total Requests:0;	Successive connection failure:0;	Total blackout seconds:0;	Last connection made:Thu Jan 01 08:00:00 CST 1970;	First connection made: Thu Jan 01 08:00:00 CST 1970;	Active Connections:0;	total failure count in last (1000) msecs:0;	average resp time:0.0;	90 percentile resp time:0.0;	95 percentile resp time:0.0;	min resp time:0.0;	max resp time:0.0;	stddev resp time:0.0]
]}ServerList:com.netflix.loadbalancer.ConfigurationBasedServerList@36eda38c

在这里插入图片描述
如果其中一个方不正常在调用的时候,在轮询调用到不正常的服务的时候就走,快速失败的方法

在这里插入图片描述

}ServerList:com.netflix.loadbalancer.ConfigurationBasedServerList@5d209707
2024-04-26 23:33:32.223 ERROR 1076 --- [ HystrixTimer-5] c.z.b.a.r.service.ReportServiceImpl      : null

com.netflix.hystrix.exception.HystrixTimeoutException: null
	at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$1.run(AbstractCommand.java:1142) ~[hystrix-core-1.5.18.jar:1.5.18]
	at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:41) ~[hystrix-core-1.5.18.jar:1.5.18]
	at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:37) ~[hystrix-core-1.5.18.jar:1.5.18]
	at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable.run(HystrixContextRunnable.java:57) ~[hystrix-core-1.5.18.jar:1.5.18]
	at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$2.tick(AbstractCommand.java:1159) [hystrix-core-1.5.18.jar:1.5.18]
	at com.netflix.hystrix.util.HystrixTimer$1.run(HystrixTimer.java:99) [hystrix-core-1.5.18.jar:1.5.18]
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_401]
	at java.util.concurrent.FutureTask.runAndReset$$$capture(FutureTask.java:308) [na:1.8.0_401]
	at java.util.concurrent.FutureTask.runAndReset(FutureTask.java) [na:1.8.0_401]
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) [na:1.8.0_401]
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) [na:1.8.0_401]
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_401]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_401]
	at java.lang.Thread.run(Thread.java:750) [na:1.8.0_401]


二 控制台 dashboard的访问

Ribbion 项目的访问地址
http://127.0.0.1:9007/amaster-report-server/actuator/hystrix.stream

在这里插入图片描述

访问成功后界面显示如下
在这里插入图片描述

OpenFegin 项目HystrixDashboard的访问地址
http://localhost:9005/amaster-work-server/hystrix

在这里插入图片描述
amaster-work-server的监控访问地址
http://localhost:9005/amaster-work-server/actuator/hystrix.stream

在这里插入图片描述

在amaster-work-serve 项目上配置的hystrixDashBoad ,也可以访问report-Server上的监控

http://127.0.0.1:9007/amaster-report-server/actuator/hystrix.stream
在这里插入图片描述
所以只要配置开启了hystrixDashBoad的项目 ,可以访问hystrixDashBoad 监控界面的项目,它本质上也是一个监控hystrixDashBoad监控展示项目,只要被访问的服务配置了Actor的监控都可以访问

  • 11
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值