Spring Cloud与微服务构建(八)熔断器Hystrix 8.5 在RestTemplate和Ribbon上使用熔断器

本节以案例的形式讲解如何在RestTemplate和Ribbon作为服务消费者时使用Hystrix熔断器。本节的案例在上一章的案例基础之上进行改造。在上一章的eureka-ribbon-cliennt工程中,我们使用RestTemplate调用了eureka-client的“/hi”API接口,并用Ribbon做了负载均衡,本节在此基础上加Hystrix熔断器的功能。

首先在工程pom文件中引用Hystrix的起步依赖spring-cloud-starter-hystrix,代码如下:

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

然后在Spring Boots的启动类EurekaRibbonClientApplication加上@EnableHystrix注解开启Hystrix的熔断器功能,代码如下:

@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
public class EurekaRibbonClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaRibbonClientApplication.class, args);
    }

}

修改RibbonService的代码,在hi()方法上加@HystrixCommand注解。有了@HystrixCommand注解,hi()方法就启用Hystrix熔断器的功能,其中,fallbackMethod为处理回退(fallback)逻辑的方法。在本例中,直接返回了一个字符串。在熔断器打开的状态下,会执行fallback逻辑。fallback的逻辑最好是返回一些静态的字符串,不需要处理复杂的逻辑,也不需要远程调度其他服务,这样方便执行快速失败,释放线程资源。如果一定要在fallback逻辑中远程调度其他服务,最好在远程调度其他服务时,也加上熔断器。案例代码如下:

@Service
public class RibbonService {
    @Autowired
    RestTemplate restTemplate;
    @HystrixCommand(defaultFallback = "hiError")
    public String hi(String name){
        return restTemplate.getForObject("http://eureka-client/hi?name="+name,String.class);
    }
    
    public String hiError(String name){
        return "hi,"+name+",sorry,error!";
    }
}

依次启动工程eureka-server、eureka-client、eureka-ribbon-client。等所有的工程都启动完毕,在浏览器上访问http://localhost:8764/hi,浏览器会显示:

hi mengzhitk,i am from port:8762

关闭eureka-client,即它处于不可用的状态,此时eureka-ribbon-client无法调用eureka-client的“/hi”接口,访问http://localhost:8764/hi,浏览器会显示:

hi,mengzhitk,sorry,error!

由此可见,当eureka-client不可用时,调用eureka-ribbon-client的“/hi”接口会进入RibbonService类的"/hi"方法中。由于eureka-client没有响应,判定eureka-client不可用,开启了熔断器,最后进入了fallbackMethod的逻辑。当熔断器打开了,之后的语法会直接执行fallbackMethod的逻辑。这样做的好处就是通过快速失败,请求能够得到及时处理,线程不再阻塞。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值