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();
}

访问效果

相关推荐
日月云棠5 小时前
各版本JDK对比:JDK 25 特性详解
java
用户8307196840826 小时前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
JavaGuide7 小时前
Claude Opus 4.6 真的用不起了!我换成了国产 M2.5,实测真香!!
java·spring·ai·claude code
IT探险家7 小时前
Java 基本数据类型:8 种原始类型 + 数组 + 6 个新手必踩的坑
java
花花无缺7 小时前
搞懂new 关键字(构造函数)和 .builder() 模式(建造者模式)创建对象
java
用户908324602737 小时前
Spring Boot + MyBatis-Plus 多租户实战:从数据隔离到权限控制的完整方案
java·后端
桦说编程8 小时前
实战分析 ConcurrentHashMap.computeIfAbsent 的锁冲突问题
java·后端·性能优化
程序员清风12 小时前
用了三年AI,我总结出高效使用AI的3个习惯!
java·后端·面试
beata13 小时前
Java基础-13: Java反射机制详解:原理、使用与实战示例
java·后端
用户03321266636713 小时前
Java 使用 Spire.Presentation 在 PowerPoint 中添加或删除表格行与列
java