前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在Feign中使用Hystrix实现服务调用容错

在Feign中使用Hystrix实现服务调用容错

作者头像
星哥玩云
发布2022-09-15 14:07:01
1650
发布2022-09-15 14:07:01
举报
文章被收录于专栏:开源部署

1、在Feign中用Hystrix实现服务调用容错

1.1、添加依赖和配置,并启用支持

1.1.1、添加依赖
代码语言:javascript
复制
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
1.1.2、添加配置
代码语言:javascript
复制
spring.application.name=hystrix
server.port=50007
eureka.client.fetch-registry=true
eureka.client.register-with-eureka=false
eureka.client.service-url.defaultZone=http://eureka01:50001/eureka/,http://eureka02:50002//eureka/
#开启支持
feign.hystrix.enabled=true
1.1.3、添加对Feign的支持
代码语言:javascript
复制
@EnableFeignClients //开启Feign支持
@SpringBootApplication
public class HystrixSpringcloudApplication {

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

1.2、添加Feign接口

代码语言:javascript
复制
@FeignClient(name = "provider")
public interface FeignClients {

    @GetMapping("/hello")
    public String hello();
}

1.3、添加Controller

代码语言:javascript
复制
@RestController
public class HelloController {

    @Autowired
    FeignClients feignClients;

    @GetMapping("/hello")
    public String index(){
        return feignClients.hello();
    }
}

1.4、实现回调类

代码语言:javascript
复制
@Component
public class HelloHstrix implements FeignClients {
    @Override
    public String hello() {
        return "出现错误!";
    }
}

1.5、添加fallback属性

代码语言:javascript
复制
@FeignClient(name = "provider",fallback = HelloHstrix.class)
public interface FeignClients {

    @GetMapping("/hello")
    public String hello();
}

1.6、测试fallbakc状态

只开启"服务中心",访问http://localhost:50007/hello,会提示错误。当把"服务提供者"也开启则会返回正确的数据。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1、在Feign中用Hystrix实现服务调用容错
    • 1.1、添加依赖和配置,并启用支持
      • 1.1.1、添加依赖
      • 1.1.2、添加配置
      • 1.1.3、添加对Feign的支持
    • 1.2、添加Feign接口
      • 1.3、添加Controller
        • 1.4、实现回调类
          • 1.5、添加fallback属性
            • 1.6、测试fallbakc状态
            相关产品与服务
            腾讯云服务器利旧
            云服务器(Cloud Virtual Machine,CVM)提供安全可靠的弹性计算服务。 您可以实时扩展或缩减计算资源,适应变化的业务需求,并只需按实际使用的资源计费。使用 CVM 可以极大降低您的软硬件采购成本,简化 IT 运维工作。
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档