美文网首页springcloud
hystrix 整合RestTemplate、OpenFeigh

hystrix 整合RestTemplate、OpenFeigh

作者: 木山手札 | 来源:发表于2020-02-09 00:32 被阅读0次

整合RestTemplate

  • 引入相关依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
  • @HystrixCommand声明该方法支持熔断,并设置熔断方法,@DefaultProperties(defaultFallback = "echoFallback")标注在类中,对类中所有的方法都使用默认的熔断方法
@Autowired
private RestTemplate restTemplate;

@HystrixCommand(fallbackMethod = "echoFallback")
@RequestMapping("/echo")
public String echo(@RequestParam("info") String message) {
   String result = restTemplate.getForObject("http://foo-service/foo/echo?message={1}", String.class, message);
   return result;
}

public String echoFallback(String messsage) {
   return "fallback method {" + messsage + "}";
}
  • 启动类使用@EnableCircuitBreaker开始对熔断的支持

整合feigh

  • 引入依赖spring-cloud-starter-netflix-hystrix
  • 定义实现feigh接口实现类,该类需要被spring容器接管
@Component
public class FooServiceFallback implements FooServiceFeign {
    @Override
    public String echo(String message) {
        return "fallback method {" + message + "}";
    }
}
  • @FeignClient注解中配置feigh接口对应的hystrix熔断接口
@FeignClient(value = "foo-service", fallback = FooServiceFallback.class)
public interface FooServiceFeign {
    @RequestMapping("/foo/echo")
    String echo(@RequestParam("message") String message);
}
  • 在feign配置中开启对hystrix支持
feign:
  hystrix:
    enabled: true
  • 启动类使用@EnableCircuitBreaker开始对熔断的支持

整合feign的接口超时熔断配置

ribbon:
 ReadTimeout: 2000 # 默认5s
 ConnectTimeout: 2000 # 默认2s
hystrix:
 command:
  default:
    execution:
      isolation:
        thread:
          timeoutInMilliseconds: 3000 # 接口调用超时时间,默认1s,还需要ribbon.readTimeout配置
    circuitBreaker:
      requestVolumeThreshold: 30 # 触发熔断最小请求次数,默认20
      errorThresholdPercentage: 30 # 请求失败占比,默认50%
      sleepWindowInMilliseconds: 10000 # 熔断多长时间后尝试请求,默认5s
  1. feign接口调用分为两层,第一层是ribbon,第二层是hystrix,ribbon超时+hystrix=feign超时
  2. 单独配置hystrix的timeoutInMilliseconds不起作用,还需要配置ribbon的ConnectTimeout、ReadTimeout
  3. ribbon参数对应的配置类CommonClientConfigKey,类中的属性首字母大写

相关文章

网友评论

    本文标题:hystrix 整合RestTemplate、OpenFeigh

    本文链接:https://www.haomeiwen.com/subject/wanwxhtx.html