spring cloud 学习(4) - hystrix 服务熔断处理

hystrix 是一个专用于服务熔断处理的开源项目,当依赖的服务方出现故障不可用时,hystrix有一个所谓的断路器,一但打开,就会直接拦截掉对故障服务的调用,从而防止故障进一步扩大(类似中电路中的跳闸,保护家用电器)。

使用步骤:(仍然在之前的示例代码上加以改造)

一、添加hystrix依赖

compile 'org.springframework.cloud:spring-cloud-starter-hystrix'

 

二、在需要熔断的方法上添加注解

package com.cnblogs.yjmyzz.spring.cloud.study.service.controller;

import com.cnblogs.yjmyzz.spring.cloud.study.dto.UserDTO;
import com.cnblogs.yjmyzz.spring.cloud.study.service.client.UserFeignClient;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

@RestController
public class OrderController {

    @Autowired
    private UserFeignClient userFeignClient;

    private final Random rnd = new Random(System.currentTimeMillis());

    @GetMapping("/order/{userId}/{orderNo}")
    @HystrixCommand(fallbackMethod = "findOrderFallback", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
    })
    public String findOrder(@PathVariable Integer userId, @PathVariable String orderNo) throws InterruptedException {
        Thread.sleep(rnd.nextInt(2000));
        UserDTO user = userFeignClient.findUser(userId);
        if (user != null) {
            return user.getUserName() + " 的订单" + orderNo + " 找到啦!";
        }
        return "用户不存在!";
    }

    public String findOrderFallback(Integer userId, String orderNo) {
        return "订单查找失败!";
    }
}  

注意findOrder上添加的HystrixCommand注解,大概意思是,如果这个方法调用失败,会切换到备用方法findOrderFallback上,而且还设置了一个超时时间1000ms,即1秒。换句话说,如果findOrder方法没有在1s内返回结果,也算调用失败,同样会切换到备用方法findOrderFallback上。

注:为了方便演示,故意在findOrder上随机停了2秒内的一段时间,所以预期这个方法,应该会偶尔超时,偶尔正常。

关于HystrixProperty的更多属性,可参考github上的官方文档:https://github.com/Netflix/Hystrix/wiki/Configuration 

 

三、main入口上启用hytrix熔断

@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
public class ServiceConsumer {

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

启用后,访问http://localhost:8002/order/1/100 ,可以看到类似以下输出:

正常时,返回类似上图的输出,如果超时,将返回下图:

此外,spring-boot的acturator也提供了health端点来查看hystrix状态,查看http://localhost:8002/health

这个表示hystrix的断路器未打开,如果 http://localhost:8002/order/1/100 这个页面狂刷(默认要5秒内失败20次以上),或者干脆把service-provider停掉,这个状态会变成:

表明此时断路器是打开的。

 

四、hystrix监控

health端点只能看到断路器的整体状态,但是对于细节展示不够详细,默认情况下,只要启用了hystrix功能,还会暴露一个端点hystrix.stream

访问 http://localhost:8002/hystrix.stream 可以查看详细的数据

注:这个页面会实时不断输出新的内容(如果有的话),首次访问的话,如果看到一直转圈,但是没有任何内容,说明这时服务对应的方法没人调用,可以访问findOrder方法后,再来看这个页面。

显然,一堆密密麻麻的文字,没有人会喜欢看,spring-cloud早就想到这一点了,提供了一个hystrix-dashboard的功能,可以用图形化的界面来解读这些数据。

再起一个项目,名为hystrix-dashboard,build.gradle参考下面:

buildscript {
    repositories {
        maven {
            url "http://maven.aliyun.com/nexus/content/groups/public/"
        }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.4.RELEASE")
    }
}

apply plugin: 'org.springframework.boot'

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:Dalston.RELEASE"
    }
}

dependencies {
    compile 'org.springframework.cloud:spring-cloud-starter-eureka'
    compile 'org.springframework.cloud:spring-cloud-starter-hystrix-dashboard'
    compile 'org.springframework.boot:spring-boot-starter-actuator'
}

main函数如下:

package com.cnblogs.yjmyzz.spring.cloud.study.hystrix;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;

/**
 * Created by yangjunming on 2017/6/30.
 */
@SpringBootApplication
@EnableHystrixDashboard
@EnableDiscoveryClient
public class HystrixDashboardApplication {
    public static void main(String[] args) {
        SpringApplication.run(HystrixDashboardApplication.class, args);
    }
}  

当然,这也是一个微服务,也可以注册到eureka上,参考下面的配置:

spring:
  application:
    name: hystrix-dashboard
server:
  port: 8035


eureka:
  instance:
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://yjmyzz:123456@server1:8100/eureka,http://yjmyzz:123456@server2:8200/eureka,http://yjmyzz:123456@server3:8300/eureka

启用成功后,访问http://localhost:8035/hystrix,会出现类似下面这个界面:

第1个输入框里,填写要监控的hystrix.steam地址,然后title这里起一个名字即可,然后点击monitor steam,就能看到图表:

这显然比纯文字友好多了。还有一个问题,如果有多个hystrix.stream地址同时监控,或者把多个地址的数据汇总起来,该怎么弄?github上有一个turbine ,就是专门为解决这个问题的,大家可以自行研究下。

最后,附上文中示例代码地址:https://github.com/yjmyzz/spring-cloud-demo

posted @ 2017-07-02 21:48  菩提树下的杨过  阅读(13367)  评论(0编辑  收藏  举报