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

访问效果

相关推荐
それども20 分钟前
@ConditionalOnWebApplication 作用
java
二哈喇子!20 分钟前
基于SSM框架的公交车查询系统的设计与实现
java·数据库·ssm
二哈喇子!30 分钟前
基于JavaSE的淘宝卖鞋后端管理系统的设计与实现
java·spring boot·spring
小冷coding32 分钟前
【Java】Dubbo 与 OpenFeign 的核心区别
java·开发语言·dubbo
Coder_Boy_36 分钟前
基于SpringAI的在线考试系统-智能考试系统-学习分析模块
java·开发语言·数据库·spring boot·ddd·tdd
cdut_suye1 小时前
解锁函数的魔力:Python 中的多值传递、灵活参数与无名之美
java·数据库·c++·人工智能·python·机器学习·热榜
逍遥德2 小时前
java Map Set List 扩容机制
java·开发语言·list
高山上有一只小老虎2 小时前
mybatisplus实现分页查询
java·spring boot·mybatis
nbsaas-boot2 小时前
基于 Java 21 ScopedValue 的多租户动态数据源完整实践
java·开发语言
2301_780669862 小时前
线程安全、线程同步(三种加锁方式)、线程池(两种创建线程池方式、线程池处理Runnable任务、线程池处理Callable任务)、并发/并行
java