Hystrix熔断、服务降级、线程隔离

初识教程

     声明下:

                 1、线程隔离已经在Hystrix内部实现了,所以这里只需要考虑熔断和降级问题; 

                 2、Hystrix主要解决雪崩问题

                 3、当消费端的请求超过降级等待时间,进行降级返回;

                 4、默认情况下当连续请求20次,超时响应率达到百分之五十则Circuit Breaker进入open状态5秒,5秒内任何请求都会收到降级响应;

1、导入依赖

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

2、注解

/*@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication*/
@SpringCloudApplication

因为SpringCloudApplication整合了上面三个注解,所以直接使用第三个SpringCloudApplication就可以了

3、添加配置-消费者

@RestController
@RequestMapping("consumer")
@DefaultProperties(defaultFallback = "queryByIdFallbackall")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;


//    @Autowired
//    private RibbonLoadBalancerClient ribbonLoadBalancerClient;l
//    @Autowired
//    private DiscoveryClient discoveryClient;

    /**
     * @PlayName queryById
     * @Author guoqiang
     * @Description //TODO
     * @Date 2019-05-13 22:43
     * @Param [id]
     * @return cn.itcast.consumer.pojo.User
     **/
    @RequestMapping("getbyid")
    @HystrixCommand(
//            fallbackMethod = "queryByIdFallback",
            commandProperties = {
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000"),
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value="60")
    })
    public String queryById(@RequestParam String id){

        String url="http://user-service/getUser?id="+id;
        String user= restTemplate.getForObject(url,String.class);
        return user;
    }
    public String queryByIdFallback(String id){
        return "忙忙忙";
    }
    public String queryByIdFallbackall(){
        return "忙忙忙全局";
    }

}

@HystrixCommand(fallbackMethod="queryUserByIdFallback"):声明一个失败回滚处理函数queryUserByIdFallback,当queryUserById执行超时(默认是1000毫秒),就会执行fallback函数,返回错误提示。

 

yml文件配置:

Ribbon的超时时间一定要小于Hystix的超时时间

hystrix:
  command:
      default:
        execution:
          isolation:
            thread:
              timeoutInMillisecond: 6000 # 设置hystrix的超时时间为6000ms

完整demo地址:

https://github.com/guoguo2008gogo/cloud-demo.git

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值