青柠开车Spring Cloud(七) —— 断路器 Hystrix

项目源码github地址

什么是Hystrix

还以商城为例:

  • 单点服务

在单点部署的商场服务项目中,如果库存模块发生错误,则会使整个商城陷入长时间的等待,或者不可用状态。

  • 分布式服务

图2

在分布式服务中,如果库存模块不可用时,将启动熔断机制,在指定时间内,将返回错误信息,并且保证整体服务的可以用性。

快速入门

spring-cloud创建spring-cloud-Hystrix模块项目,如下图:

Hystrix项目基本配置

  • pom.xml中引入Hystrixjar包

<dependencies>
    <!-- spring boot web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- 生产环境时监视和管理应用程序 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <!--hystrix-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
</dependencies>

  • application.properties配置

server.port= 8563
spring.application.name=hystrix

#配置日志级别
logging.level.org.springframework.cloud.netflix.hystrix = debug
  • HystrixApplication.java中加入@EnableCircuitBreaker注解

/**
 * @author : R&M www.rmworking.com/blog
 *         2018/9/26 10:38
 *         spring-cloud
 *         org.qnloft.hystrix
 */
@SpringBootApplication
@EnableCircuitBreaker
public class HystrixApplication{

    /**
     * 注入发起rest请求的bean
     * @return
     */
    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(HystrixApplication.class, args);
    }
}
  • Hystrix在项目中的使用示例

我们使用注入的restTemplatebean来请求 spring-web 项目的index接口

service层代码如下:


/**
 * @author : R&M www.rmworking.com/blog
 *         2018/9/26 15:30
 *         spring-cloud
 *         org.qnloft.hystrix.service
 */
@Service
public class RestWebService {

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "helloFallback" ,commandKey = "helloKey")
    public String restHelloWorldService() {
        return restTemplate.getForEntity("http://127.0.0.1:8661/index", String.class).getBody();
    }

    public String helloFallback() {
        return "访问web服务出错";
    }
}

小伙伴们应该都注意到了@HystrixCommand这个注解,这个就是在方法中增加熔断机制,fallbackMethod参数中的值是触发熔断后指定调用的方法,commandKey是为这个熔断接口的别名,在仪表盘界面会显示这个名称。

controller层代码如下:


/**
 * @author : R&M www.rmworking.com/blog
 *         2018/9/26 15:30
 *         spring-cloud
 *         org.qnloft.hystrix.controller
 */
@RestController
public class RestWebController {

    @Autowired
    private RestWebService restWebService;

    @RequestMapping(value = "hello" , method = RequestMethod.GET)
    public String getHelloWorld(){
        return restWebService.restHelloWorldService();
    }
}

如果不出意外,启动spring-web项目和spring-cloud-Hystrix项目,然后访问:http://127.0.0.1:8563/hello

那如何才能模拟熔断呢?有两种方式:最简单暴力的方式就是停止spring-web项目;另外一种温柔的方式是设置一个线程休眠3秒,因为Hystrix请求超时时间默认是2秒,这样就可以触发熔断机制了。

修改RestWebServicerestHelloWorldService方法,代码如下:


@HystrixCommand(fallbackMethod = "helloFallback")
public String restHelloWorldService() {
    // 如果让线程等待3s会发生什么呢??
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        System.out.println(e.getMessage());
    }
    return restTemplate.getForEntity("http://127.0.0.1:8661/index", String.class).getBody();
}

接下来我们再次访问:http://127.0.0.1:8563/hello

这个结果就是helloFallback方法中返回值。这样就成功触发了熔断机制。

Hystrix仪表盘

基本配置

  • pom.xml中加入dashboard的jar包:

<!-- Hystrix 仪表盘 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
  • HystrixApplication.java中加入@EnableHystrixDashboard注解,并且加入如下代码:
/**
 * 将HystrixMetricsStreamServlet注册到Servlet,否则会出现访问hystrix.stream 404问题
 * @return
 */
@Bean
public ServletRegistrationBean<HystrixMetricsStreamServlet> getHystrixStreamServlet(){

    HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
    ServletRegistrationBean<HystrixMetricsStreamServlet> registrationBean = new ServletRegistrationBean<>(streamServlet);
    registrationBean.setLoadOnStartup(1);
    registrationBean.addUrlMappings("/hystrix.stream");
    registrationBean.setName("HystrixMetricsStreamServlet");
    return registrationBean;
}

将HystrixMetricsStreamServlet注册到Servlet,否则会出现访问hystrix.stream 404问题

仪表盘的使用

当出现如下页面时,则证明配置成功。

首先Hystrix Dashboard提供三种不同的监控方式:

因为我们没有集群环境,暂时先使用单体应用监控。在图中红框中输入http://127.0.0.1:8563/hystrix.stream ,点击页面最下面的Monitor Stream按钮,之后进入监控界面,如下图:

此时Hystrix Dashboard已经处于监控状态,小伙伴可以看一下CPU占用率,idea控制台也会有显示:

现在我们访问一下:http://127.0.0.1:8563/hello 这个地址,再看一下监控台会出现变化

这是监控到接口helloKey被访问。更多功能小伙伴们根据工作需求,自行探索。

原文地址:https://www.cnblogs.com/qnloft/p/qing-ning-kai-cheSpring-Cloud-qi--duan-lu-qi-Hystr.html