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

访问效果

相关推荐
ZZHow10241 小时前
JavaWeb开发_Day05
java·笔记·web
CHEN5_021 小时前
【Java虚拟机】垃圾回收机制
java·开发语言·jvm
Warren981 小时前
Lua 脚本在 Redis 中的应用
java·前端·网络·vue.js·redis·junit·lua
艾伦~耶格尔5 小时前
【数据结构进阶】
java·开发语言·数据结构·学习·面试
爪洼传承人6 小时前
18- 网络编程
java·网络编程
smileNicky6 小时前
SpringBoot系列之从繁琐配置到一键启动之旅
java·spring boot·后端
祈祷苍天赐我java之术6 小时前
Java 迭代器(Iterator)详解
java·开发语言
David爱编程7 小时前
为什么必须学并发编程?一文带你看懂从单线程到多线程的演进史
java·后端
我命由我123457 小时前
软件开发 - 避免过多的 if-else 语句(使用策略模式、使用映射表、使用枚举、使用函数式编程)
java·开发语言·javascript·设计模式·java-ee·策略模式·js
long3167 小时前
java 策略模式 demo
java·开发语言·后端·spring·设计模式