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

访问效果

相关推荐
pianmian11 小时前
类(JavaBean类)和对象
java
我叫小白菜2 小时前
【Java_EE】单例模式、阻塞队列、线程池、定时器
java·开发语言
Albert Edison2 小时前
【最新版】IntelliJ IDEA 2025 创建 SpringBoot 项目
java·spring boot·intellij-idea
超级小忍3 小时前
JVM 中的垃圾回收算法及垃圾回收器详解
java·jvm
weixin_446122463 小时前
JAVA内存区域划分
java·开发语言·redis
勤奋的小王同学~3 小时前
(javaEE初阶)计算机是如何组成的:CPU基本工作流程 CPU介绍 CPU执行指令的流程 寄存器 程序 进程 进程控制块 线程 线程的执行
java·java-ee
TT哇3 小时前
JavaEE==网站开发
java·redis·java-ee
2401_826097623 小时前
JavaEE-Linux环境部署
java·linux·java-ee
缘来是庄4 小时前
设计模式之访问者模式
java·设计模式·访问者模式
Bug退退退1234 小时前
RabbitMQ 高级特性之死信队列
java·分布式·spring·rabbitmq