Hystrix使用笔记与填坑之旅

#Hystrix使用笔记与填坑之旅

最近在整理学习spring cloud Finchley正式版相关的知识内容,也踩了不少的坑,现在先记录正确的使用情况,然后再后边记录注意事项与填坑之旅:


##一、服务容错、服务降级与超时设置
首先导入hystix依赖:

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

main主类加入注解:

@EnableCircuitBreaker

注意:@SpringCloudApplication等同于@SpringBootApplication,@EnableDiscoveryClient,@EnableCircuitBreaker这三个注解

在这里建立HystrixController来测试Hystrix各种配置:

@RestController
// 设置默认的全局降级触发函数
@DefaultProperties(defaultFallback = "defaultFallback") 
public class HystrixController {

	//设置超时时间
    @HystrixCommand(commandProperties = @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000"))
    //为指定方法设置降级函数
//  @HystrixCommand(fallbackMethod = "fallback")
	//服务断路器模式设置
//  @HystrixCommand(commandProperties = {
			  //设置断路器生效
//            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),		
			  //一个统计窗口内熔断触发的最小个数3/10s
//            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "3"),
			  //熔断5秒后去尝试请求
//            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000"),
			  //失败率达到30百分比后熔断
//            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "30"),})
	//当配置文件设置参数之后,可以直接使用@HystrixCommand注解来使服务熔断生效
//  @HystrixCommand
    @GetMapping(value = "productOrderlist")
    public String getProductOrderList(@RequestParam Integer number) {
        if (number % 2 == 0) {
            return "success";
        }
        RestTemplate restTemplate = new RestTemplate();
        //throw new RuntimeException("发送异常");
        return restTemplate.postForObject("http://127.0.0.1:9080/product/listForOrder", Arrays.asList("157875196366160022"),String.class);
    }
    private String fallback() {
        return "网络开小差了,请稍后重试···";
    }
    private String defaultFallback() {
        return "defaultFallback: 网络开小差了,请稍后重试···";
    }
}

如果只使用配置文件的话这样设置(即:方法只使用@HystrixCommand):

# 以配置hystrix超时时间为例
hystrix:
  command:
    #默认的超时时间设置
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 1000
    # commandKey,默认为方法名
    getProductOrderList:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 3000

##二、使用Hystrix-Feign

**作用:**前篇讲feign时已经提到过,将feign与hystrix整合,当A服务使用feign调用B服务时,B服务中的接口出错,使用Hystrix对服务降级处理,下面讲使用方式:

首先配置A服务与B服务的配置文件:

feign:
  hystrix:
    enabled: true

配置B服务(即被调用的一方)的FeignClient端

/**
 * Created by wholve
 * 2018-6-10 21:04
 */
@FeignClient(name = "product-server", fallback = ProductClient.ProductClientFallback.class)
public interface ProductClient {

    @PostMapping("/product/listForOrder")
    List<ProductInfoOutput> listForOrder(@RequestBody List<String> productIdList);

    @PostMapping("/product/decreaseStock")
    void decreaseStock(@RequestBody List<DecreaseStockInput> decreaseStockInputList);

    @Component
    static class ProductClientFallback implements ProductClient {

        @Override
        public List<ProductInfoOutput> listForOrder(List<String> productIdList) {
            return null;
        }

        @Override
        public void decreaseStock(List<DecreaseStockInput> decreaseStockInputList) {

        }
    }
}

这里@FeignClient注解中fallback的value对应的值为服务熔断之后的触发类,该类实现FeignClient注释的接口,实现的方法就是服务降级之后触发的方法。

##三、使用HystrixDashBoard

使用HystrixDashBoard可以有效的观测服务熔断情况,下面记录一下具体配置:

首先导入依赖:

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

然后在main主类加入注解:

@EnableHystrixDashboard

配置文件配置:

management:
  endpoints:
    web:
      exposure:
        include: "*"

启动,配置首页:
http://localhost:9999/actuator/hystrix.stream

监控:http://localhost:9999/actuator/hystrix.stream
Delay: 1000ms
Title: order-service

最后,调用@HystrixCommand注解的方法触发断路器,即可监控到效果

##四、填坑之旅

上面已经详细记录了关于Hystrix基本使用,由于之前使用的并不是 Finchley正式版,所以有些配置有不一样的地方做一下说明:

1、关于Hystrix DashBoard依赖,早期版本使用如下依赖:

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

但正式版使用的是:

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

所以大家不要搞错了,不然dashboard不会生效

2、 找不到@EnableHystrixDashboard

正式由于版本问题,改为spring-cloud-starter-netflix-hystrix-dashboard依赖之后可能maven库并没有更新下载,所以导致jar下载不下来,解决方式:删除hystrix相关的maven仓库中心下载,如果还是不行,将所有spring cloud相关仓库文件删除。

3、 配置DashBoard监控路径
刚开始查阅网上资料配置context-path没有生效,最终使用的是actuator监控,即

http://ip:port/actuator/hystrix.stream
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值