使用openfeign集成sentinel或者hystrix实现服务降级

版本

spring-boot 2.6.3
spring-cloud-alibaba 2021.0.1

OpenFeign

导入依赖

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

// Spring Cloud 2020版本以后,默认移除了对Netflix的依赖,其中就包括Ribbon,官方默认推荐使用Spring Cloud Loadbalancer正式替换Ribbon,并成为了Spring Cloud负载均衡器的唯一实现。
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-loadbalancer</artifactId>
</dependency>

配置文件

# Feign 配置
feign:
  client:
    config:
      default:
      #简历连接所用的时间,适用于网络状况正常的情况下,两端连接所需要的时间
        ConnectTimeOut: 5000
      #指建立连接后从服务端读取到可用资源所用的时间
        ReadTimeOut: 10000

开启OpenFeign

在启动类上使用 @EnableFeignClients 注解

hystrix

添加依赖

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

配置文件

  • 以前开启openfeign对hystrix的支持(这样的方式yml是没有提示的)
feign:
  hystrix:
    enabled: true
feign:
  circuitbreaker:
    enabled: true

开启支持

在启动类型上使用 @EnableHystrix 注解开启Hystrix的使用

sentinel

添加依赖

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

配置文件

// 开启sentinel的支持
feign:
  sentinel:
    enabled: true

开启支持

在启动类上使用 @EnableFeignClients 注解开启OpenFeign的使用

服务降级处理

方式一

  • 定义接口
// 注解属性解释-name :服务端服务名称;fallback :当feign调用失败后触发的保底方法,防止服务调用失败影响整个功能的使用
@FeignClient(name = "user-server",fallback = FallbackClient.class,path = "/user")
public class UserClient {
	
	@Post("/test")
	String test();
}
  • 定义降级方法
@Component
public class UserFallbackClient implements UserClient{
	@Override
    public String test() {
        return "降级feign远程调用系统日志服务异常后的降级方法";
    }
}

方式二

  • 定义接口
@FeignClient(name = "user-server",fallbackFactory= FallbackClient.class,path = "/user")
public class UserClient {
	
	@Post("/test")
	String test();
}
  • 定义降级方法
@Component
public class UserFallbackClient implements FallbackFactory<UserClient>{
	 @Override
    public LogClient create(Throwable cause) {
        return new UserClient() {
           @Override
		   public String test() {
		       return "降级feign远程调用系统日志服务异常后的降级方法";
		   }
        };
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值