OpenFeign整合Sentinel

OpenFeign 整合 Sentinel 实现服务降级

引入依赖

XML 复制代码
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- nacos服务发现 -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>

    <!-- openfeign 服务调用 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    <!--sentinel 服务保护 -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
    </dependency>
</dependencies>

打开配置

java 复制代码
spring:
  application:
    name: order-feign-sentinel
  cloud:
    nacos:
      server-addr: 127.0.0.1:8847
      discovery:
        username: nacos
        password: nacos

# springboot 默认日志级别是info  因此 feign的debug日志级别就不会输出
logging:
  level:
    com.learning.springcloud.order.feign: debug

# openfeign 整合 sentinel
feign:
  sentinel:
    enabled: true

编写接口

  • stock-nacos 接口类
java 复制代码
@RestController
@RequestMapping("/stock")
public class StockController {
    @Value("${server.port}")
    String serverPort;

    @RequestMapping("/reduct2")
    public Object reductStock2() {
        int a = 1 / 0; // 故意制造异常
        System.out.println(serverPort + ":扣减库存2成功了");
        return "reduct2 stock success. stock service port:" + serverPort;
    }
}
  • OpenFeigin 接口类
java 复制代码
@FeignClient(name = "stock-nacos", path = "/stock", configuration = FeignConfig.class)
public interface StockFeignService {
    
    @RequestMapping("/reduct2")
    String reductStock2();
}
  • 服务降级处理类 实现OpenFeigin 接口类 并 托管Spring容器
java 复制代码
@Component
public class StockFeignServiceForback implements StockFeignService {
    @Override
    public String reductStock2() {
        return "降级了!!!";
    }
}
  • OpenFeign 接口类 增加 fallback 属性, 值为服务降级处理类
java 复制代码
// fallback = StockFeignServiceForback.class
@FeignClient(name = "stock-nacos", path = "/stock", configuration = FeignConfig.class,
        fallback = StockFeignServiceForback.class)
public interface StockFeignService {
    @RequestMapping("/reduct2")
    String reductStock2();
}

访问效果

相关推荐
RainCity9 小时前
Java Swing 自定义组件库分享(九)
java·笔记·后端
NE_STOP9 小时前
Docker--容器常用命令
java
摇滚侠10 小时前
MSYS2 Builds Hashes Cygwin Builds Hashes 区别
java
武子康10 小时前
Java-08 深入浅出 Mybatis 数据库多对多关系设计:中间表、映射与性能优化
java·后端·spring
无极低码10 小时前
wsdl转client使用wsimport,高版本openjdk不支持使用 JAX-WS
java
明夜之约10 小时前
Spring Cloud Gateway 深度解析:从路由原理到生产级网关实战
java·spring·spring cloud·gateway
Simon5231410 小时前
Spring Bean----5.27学习小记
java·学习·spring
ZJH__GO10 小时前
java项目-流水线线程池
java·开发语言
●VON10 小时前
鸿蒙NEXT ArkUI进阶:用CustomBuilder打造高定制化品牌页签栏
java·华为·harmonyos·鸿蒙·新特性
夕除11 小时前
spring boot 16
java·spring boot·后端