Spring cloud系列十 使用@HystrixCommand使用Hystrix组件及@EnableCircuitBreaker原理介绍

1. 概述

本文主要包括如下内容:

  • 1 通过@HystrixCommand注解实现在Spring Cloud中使用Hystrix组件:包括通过@HystrixCommand调用服务,实现fallback方法
  • 2 如何通过配置自定义的Hystrix参数
  • 3 对@HystrixCommand+@EnableCircuitBreaker的原理进行介绍

2. 通过@HystrixCommand注解实现在Spring Cloud使用Hystrix组件相关的工程

  • cloud-registration-center:注册中心
  • cloud-service-hystrix: 作为服务方的工程
  • cloud-consumer-hystrix:通过hystrix调用cloud-service-hystrix的接口

3. cloud-registration-center

注册中心,此工程之前已经介绍过了,这里略

4. cloud-service-hystrix

作为服务方的工程,此工程比较简单,详细的创建方法见这节Spring cloud系列一 包含所有基本要素的完整Spring Cloud demo
其他和例子有关的配置如下:

4.1. bootstrap-hystrix.yml

只列出部分内容

spring:
  application:
    # 本服务注册到注册到服务器的名称, 这个名称就是后面调用服务时的服务标识符
    name: cloud-hystrix-service
….

4.2. SimpleCtl:提供服务的Control类

@RestController
public class SimpleCtl {
    private AtomicInteger count = new AtomicInteger();
    private AtomicInteger sleepCount = new AtomicInteger();

    @RequestMapping(value="/hystrix/simple")
    public String hystrixClientCall(@RequestParam("time") long time){
        int newCount = count.incrementAndGet();
        return "time " + time + " hystrix" + newCount + ": " + ThreadLocalRandom.current().nextInt(1000);
    }
……
}

5. cloud-consumer-hystrix

通过hystrix调用cloud-service-hystrix的接口

5.1. pom.xml:只列出关键的jar

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

5.2. bootstrap-hystrix-simple.yml属性配置

# port
server:
  port: 12083

spring:
  application:
    # 本服务注册到注册到服务器的名称, 这个名称就是后面调用服务时的服务标识符
    name: cloud-consumer-hystrix
eureka:
  client:
    serviceUrl:
      # 服务器注册/获取服务器的zone
      defaultZone: http://127.0.0.1:10761/eureka/
  instance:
    prefer-ip-address: true

5.3. MyHystrixClient

功能:通过RestTemplate调用服务的接口

  • @HystrixCommand:此注解表示此方法是hystrix方法,其中fallbackMethod定义回退方法的名称
  • String myFallback(long p, Throwable e) :HystrixCommand的回退方法,此方法必须和hystrix的执行方法在相同类中。可以把HystrixCommand的执行参数和执行失败的异常传入回退方法中
@Service
  • 5
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值