Spring Cloud(三):熔断器Hystrix

  一:简介:

          在分布式系统当中,服务与服务之间的依赖错综复杂,一种不可避免的情况就是某些服务会出现故障,导致依赖他们的其他服务也出现远程调度的线程阻塞。Hystrix是通过隔离服务的访问点阻止联动故障的。并提供了故障的解决方案。

  二:Hystrix的设计原则

  1.  防止单个服务的故障耗尽整个服务的Servlet容器(例如Tomcat)的线程资源
  2. 快速失败机制,如果某个服务出现故障,则调用该服务的请求快速失败,而不是线程等待
  3. 提供回退(fallback方案),在请求发生故障时,提供设定好的回退方案
  4. 提供熔断机制,防止故障扩散到其他服务
  5. 提供熔断器的监控组件,可以实时监控熔断器的状态

三:在RestTemplat和Ribbon上使用熔断器

     案例基于上一章节的项目体系,对eureka-consumer模块进行改造。

    1.pom文件引入Hystrix依赖:

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

    2.启动类开启熔断器。

   3.调用服务的请求上添加熔断器机制,并设置失败函数。

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class HelloService {

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "helloError")
    public String hello(String name){
        return restTemplate.getForObject("http://SERVICE-PROVIDER/provider?name=" + name, String.class);
    }

    public String helloError(String name){
        return "服务器出现异常...异常参数:"+name;
    }
}

启动eureka-consumer消费者,关闭服务提供者,启动eureka注册中心。

访问请求,可以看见执行了熔断器请求异常的处理函数:

四:在Fegin上使用熔断器。

当引入Fegin的依赖的时候,已经引入了Hystrix的依赖,所以不需要额外引入Hystrix的依赖。

改造eureka-feign模块:

application.yml配置文件开启feign的熔断机制:

server:
  port: 8091
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
spring:
  application:
    name: client-feign

feign:
  hystrix:
    enabled: true

创建HelloService接口的实现类:

import org.springframework.stereotype.Component;

@Component
public class HelloServiceImpl implements HelloService {
    @Override
    public String hello(String name) {
        return "feign 访问服务器失败了,异常参数是:"+ name;
    }
}

HelloService中设置请求异常的调用:

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(value = "SERVICE-PROVIDER", fallback = HelloServiceImpl.class)
public interface HelloService {

    @RequestMapping(value = "/provider", method = RequestMethod.GET)
    String hello(@RequestParam(value = "name") String name);
}

开启该服务,访问http://localhost:8091/feign?name=zhang可以看见浏览器打印异常信息:

feign 访问服务器失败了,异常参数是:zhang

思考:

Spring Cloud的熔断器只是提供了快速失败,当在集群环境当中,并没有实现一个服务节点不可用的时候,访问同一服务的其它节点的机制。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值