1、spring cloud---feign+Hystrix熔断器实现(第三章)

本文介绍如何在Spring Cloud项目中使用Feign结合Hystrix实现服务调用的熔断机制。通过配置启用Hystrix,创建回调类并指定fallback属性,可在服务不可用时返回预定义消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Feign-Hystrix

本文中示例代码的引用版本:
org.springframework.boot 版本 :2.1.0.RELEASE
org.springframework.cloud 版本:Greenwich.M1

示例代码-码云 https://gitee.com/sharps/springcloud

因为熔断只是作用在服务调用这一端,因此我们根据上一篇的示例代码只需要改动spring-cloud-consumer项目相关代码就可以。因为,Feign中已经依赖了Hystrix所以在maven配置上不用做任何改动。

1、配置文件
application.properties添加这一条:

feign.hystrix.enabled=true

2、创建回调类
创建HelloRemoteHystrix类继承与HelloRemote实现回调的方法

@Component
public class HelloRemoteHystrix implements HelloRemote{

    @Override
    public String hello(@RequestParam(value = "name") String name) {
        return "hello" +name+", this messge send failed ";
    }
}

3、添加fallback属性
在HelloRemote类添加指定fallback类,在服务熔断的时候返回fallback类中的内容。

@FeignClient(name= "spring-cloud-producer",fallback = HelloRemoteHystrix.class)
public interface HelloRemote {

    @RequestMapping(value = "/hello")
    public String hello(@RequestParam(value = "name") String name);

}

改动点就这点,很简单吧。

4、测试
那我们就来测试一下看看效果吧。

依次启动0301spring-cloud-eureka、0302spring-cloud-producer、0303spring-cloud-consumer-hystrix三个项目。

浏览器中输入:http://localhost:9091/hello/llx

返回:hello llx,this is first messge!

说明加入熔断相关信息后,不影响正常的访问。接下来我们手动停止spring-cloud-producer项目再次测试:

浏览器中输入:http://localhost:9091/hello/llx

返回:hello llx, this messge send failed!

根据返回结果说明熔断成功。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值