OpenFeign和Gateway集成Sentinel实现服务降级

news2025/6/3 19:43:46

目录

    • OpenFeign集成Sentinel实现fallback服务降级
      • cloud-alibaba-payment8003(支付服务)
      • cloud-common-api(通用模块)
      • cloud-alibaba-order9003(订单服务)
      • Sentinel配置流控规则
      • 测试结果
    • Gateway集成Sentinel实现服务降级
      • cloud-gateway9527(网关)
      • 测试结果
    • 总结

在这里插入图片描述

OpenFeign集成Sentinel实现fallback服务降级


cloud-alibaba-payment8003(支付服务)

1. 引入依赖

<!--SpringCloud alibaba sentinel -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- nacos-discovery -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- 引入自己定义的api通用包 -->
<dependency>
    <groupId>com.zzyy.cloud</groupId>
    <artifactId>cloud-common-api</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>
<!--SpringBoot通用依赖模块-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--lombok-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<!--test-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

2. yml配置

server:
  port: 8003

spring:
  application:
    name: nacos-payment-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848  # 配置nacos地址
    sentinel:
      transport:
        dashboard: localhost:8080  #配置Sentinel dashboard控制台服务地址
        port: 8719  #默认8719端口,如果被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口

3. 主启动类

@SpringBootApplication
@EnableDiscoveryClient
public class Main8003 {

    public static void main(String[] args) {
        SpringApplication.run(Main8003.class, args);
    }
}

4. 控制类 PayController

@RestController
public class PayController {

    @Value("${server.port}")
    private String port;

    @GetMapping("/pay/nacos/{id}")
    @SentinelResource(value = "PaySentinelResource", blockHandler = "payBlockHandler")
    public String getPayInfo(@PathVariable("id") Integer id) {
        return "支付端口" + port + ",订单" + id + "已付款/(O v O)/~~";
    }

    public String payBlockHandler(@PathVariable("id") Integer id, BlockException blockException) {
        return "支付服务限流,请稍后再试/(T o T)/~~";
    }
}

cloud-common-api(通用模块)

1. 引入依赖

<!--SpringBoot通用依赖模块-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- SpringCloud openfeign -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

2. Feign 接口 PayFeignSentinelApi

@FeignClient(value = "nacos-payment-service", fallback = PayFeignSentinelApiFallback.class)
public interface PayFeignSentinelApi {

    @GetMapping("/pay/nacos/{id}")
    public String getPayInfo(@PathVariable("id") Integer id);
}

3. 全局统一服务降级类 PayFeignSentinelApiFallback

@Component
public class PayFeignSentinelApiFallback implements PayFeignSentinelApi {

    @Override
    public String getPayInfo(Integer id) {
        return "支付服务异常,服务降级...";
    }
}

cloud-alibaba-order9003(订单服务)

1. 引入依赖

<!-- 引入自己定义的api通用包 -->
<dependency>
    <groupId>com.zzyy.cloud</groupId>
    <artifactId>cloud-common-api</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>
<!--SpringCloud alibaba sentinel -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- SpringCloud openfeign -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- nacos-discovery -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- loadbalancer -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<!-- web + actuator -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--lombok-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

2. yml配置

server:
  port: 9003

spring:
  application:
    name: nacos-order-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
#订单模块也要引入Sentinel依赖,激活Sentinel对Feign的支持,否则Feign接口fallback将失效
feign:
  sentinel:
    enabled: true

3. 主启动类

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class Main9003 {

    public static void main(String[] args) {
        SpringApplication.run(Main9003.class, args);
    }
}

4. 控制类 OrderController

@RestController
public class OrderController {

    @Resource
    private PayFeignSentinelApi payFeignSentinelApi;

    @GetMapping("/order/pay/nacos/feign/{id}")
    public String getPayInfoByFeign(@PathVariable("id") Integer id) {
        String result = payFeignSentinelApi.getPayInfo(id);
        return "订单支付信息查询结果:" + result;
    }
}

Sentinel配置流控规则

在这里插入图片描述
在这里插入图片描述

测试结果

  • 访问 http://localhost:9003/order/pay/nacos/feign/123 返回:订单支付信息查询结果:支付端口8003,订单123已付款/(O v O)/~~
  • 连续快速访问 http://localhost:9003/order/pay/nacos/feign/123 返回:订单支付信息查询结果:支付服务限流,请稍后再试/(T o T)/~~
  • 关闭支付服务8003(模拟宕机),访问 http://localhost:9003/order/pay/nacos/feign/123 返回:订单支付信息查询结果:支付服务异常,服务降级…

Gateway集成Sentinel实现服务降级


cloud-gateway9527(网关)

1. 引入依赖

<!-- gateway -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-transport-simple-http</artifactId>
    <version>1.8.8</version>
</dependency>
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
    <version>1.8.8</version>
</dependency>

2. yml配置

server:
  port: 9527

spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      routes:
        - id: pay_routh1  # 路由的ID(类似mysql主键ID),没有固定规则但要求唯一,建议配合服务名
          uri: http://localhost:8003
          predicates:
            - Path=/pay/**  # 断言,路径相匹配的进行路由

3. 主启动类

@SpringBootApplication
@EnableDiscoveryClient
public class Main9527 {

    public static void main(String[] args) {
        SpringApplication.run(Main9527.class, args);
    }
}

4. 配置类 GatewayConfiguration

@Configuration
public class GatewayConfiguration {

    private final List<ViewResolver> viewResolvers;
    private final ServerCodecConfigurer serverCodecConfigurer;

    public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                ServerCodecConfigurer serverCodecConfigurer) {
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
        // Register the block exception handler for Spring Cloud Gateway.
        return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
    }

    @Bean
    @Order(-1)
    public GlobalFilter sentinelGatewayFilter() {
        return new SentinelGatewayFilter();
    }

    @PostConstruct
    public void doInit() {
        initBlockHandler();
    }

    //处理+自定义返回的例外信息,类似我们的调用触发了流控规则保护
    private void initBlockHandler() {
        Set<GatewayFlowRule> rules = new HashSet<>();
        rules.add(new GatewayFlowRule("pay_routh1").setCount(2).setIntervalSec(1));
        GatewayRuleManager.loadRules(rules);
        BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                HashMap<String, String> map = new HashMap<>();
                map.put("errorCode", HttpStatus.TOO_MANY_REQUESTS.getReasonPhrase());
                map.put("errorMsg", "系统繁忙,触发限流...");
                return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
                                      .contentType(MediaType.APPLICATION_JSON)
                                      .body(BodyInserters.fromValue(map));
            }
        };
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }
}

测试结果

  • 访问 http://localhost:9527/pay/nacos/999 返回:支付端口8003,订单999已付款/(O v O)/~~
  • 连续快速访问 http://localhost:9527/pay/nacos/999 返回:{“errorCode”: “Too Many Requests”, “errorMsg”: “系统繁忙,触发限流…”}

总结


以上主要介绍了 OpenFeign 和 Gateway 集成 Sentinel 实现服务降级的相关知识,想了解更多 Sentinel 知识的小伙伴请参考 Sentinel 官网 和 Spring Cloud Alibaba 官网 进行学习,学习更多 Spring Cloud 实战实用技巧的小伙伴,请关注后期发布的文章,认真看完一定能让你有所收获。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2395575.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

CS144 - LAB0

CS144 - Lab 0 telnet 发送请求 如图&#xff0c;很简单&#xff0c;但是注意输入时间太久会超时 发邮箱 首先我们需要用命令行去发邮箱&#xff0c;这里我用企业微信邮箱给自己的 qq 邮箱发送~ 整个命令如下&#xff01; 对于其中的参数&#xff0c;其实从英文就可以看出来…

论文浅尝 | 将复杂知识图谱问答对齐为约束代码生成(COLING2025)

笔记整理&#xff1a;康家溱&#xff0c;东南大学在读硕士&#xff0c;研究方向为代码大语言模型 论文链接&#xff1a;https://aclanthology.org/2025.coling-main.267.pdf 发表会议&#xff1a;COLING 2025 1. 动机 近年来&#xff0c;随着大语言模型&#xff08;LLM&#xf…

Golang|分布式搜索引擎中所使用到的设计模式

迭代器模式 定义&#xff1a;在遍历接口时&#xff0c;提供统一的方法函数供调用&#xff0c;保持一致性。核心思想&#xff1a;与大众习惯保持一致&#xff0c;方便第三方实现容器类时保持一致。常见方法&#xff1a;如next()方法&#xff0c;适用于所有集合类&#xff0c;简化…

Ubuntu22.04通过命令行安装qt5

环境&#xff1a; VMware17Pro ubuntu-22.04.5-desktop-amd64.iso 步骤&#xff1a; 安装好虚拟机进入shell&#xff0c;或通过ssh登录&#xff0c;确保虚拟机能上外网&#xff0c;执行命令&#xff1a; sudo apt update sudo apt install build-essential sudo snap in…

STM32:ESP8266 + MQTT 云端与报文全解析

知识点1【MQTT的概述】 1、概述 MQTT是一种基于发布/订阅模式的轻量级应用层协议&#xff0c;运行在TCP/IP协议之上&#xff0c;专用物联网&#xff08;IoT&#xff09;和机器对机器&#xff08;M2M&#xff09;设计&#xff0c;其核心目标是低带宽&#xff0c;高延迟或不稳定…

HTML5 Canvas 星空战机游戏开发全解析

HTML5 Canvas 星空战机游戏开发全解析 一、游戏介绍 这是一款基于HTML5 Canvas开发的2D射击游戏&#xff0c;具有以下特色功能&#xff1a; &#x1f680; 纯代码绘制的星空动态背景✈️ 三种不同特性的敌人类型&#x1f3ae; 键盘控制的玩家战机&#x1f4ca; 完整的分数统…

箱式不确定集

“箱式不确定集&#xff08;Box Uncertainty Set&#xff09;”可以被认为是一种 相对简单但实用的不确定集建模方式。 ✅ 一、什么是“简单的不确定集”&#xff1f; 在鲁棒优化领域&#xff0c;“简单不确定集”通常指的是&#xff1a; 特点描述形式直观数学表达简洁&#…

内存管理 : 04段页结合的实际内存管理

一、课程核心主题引入 这一讲&#xff0c;我要给大家讲的是真正的内存管理&#xff0c;也就是段和页结合在一起的内存管理方式。之前提到过&#xff0c;我们先学习了分段管理内存的工作原理&#xff0c;知道操作系统采用分段的方式&#xff0c;让用户程序能以分段的结构进行编…

vue3: baidusubway using typescript

项目结构&#xff1a; <!--npm install -D tailwindcss-3d BaiduSubwayMap.vue npm install -D tailwindcss postcss autoprefixer--> <template><div class"relative w-full h-screen"><!-- 地图容器 --><div id"subway-container…

Redis最佳实践——性能优化技巧之集群与分片

Redis集群与分片在电商应用中的性能优化技巧 一、Redis集群架构模式解析 1. 主流集群方案对比 方案核心原理适用场景电商应用案例主从复制读写分离数据冗余中小规模读多写少商品详情缓存Redis Sentinel自动故障转移监控高可用需求场景订单状态缓存Redis Cluster原生分布式分片…

常见相机的ISP算法

常见的ISP算法 3A算法 去雾算法 图像增强算法 图像宽动态算法 图像的电子缩放算法&#xff0c;无极电子缩放 图像降噪算法 相机常见问题 1.相机启动速度问题&#xff0c;启动速度较慢 2.相机扛不住高低温问题 3.相机散热问题问题 4.相机高低温芯片保护掉电 5.相机的成像效果或者…

2024 CKA模拟系统制作 | Step-By-Step | 8、题目搭建-创建 Ingress

目录 ​​​​​​免费获取题库配套 CKA_v1.31_模拟系统 一、题目 二、核心考点 Ingress 资源定义 Ingress Controller 依赖 服务暴露验证 网络层次关系 三、搭建模拟环境 1.创建命名空间 2.安装ingress ingress-nginx-controller 3.创建hello.yaml并部署 四、总结 …

OldRoll复古胶片相机:穿越时光,定格经典

在数字摄影盛行的今天&#xff0c;复古胶片相机的独特魅力依然吸引着无数摄影爱好者。OldRoll复古胶片相机这款软件&#xff0c;以其独特的复古风格和丰富的胶片滤镜效果&#xff0c;让用户仿佛穿越回了那个胶片摄影的黄金时代。它不仅模拟了胶片相机的操作界面&#xff0c;还提…

通俗易懂的 JS DOM 操作指南:从创建到挂载

目录 &#x1f9e9; 1. 创建元素&#xff1a;document.createElement / createElementNS &#x1f4dd; 2. 创建文本&#xff1a;document.createTextNode ✏️ 3. 修改文本&#xff1a;node.nodeValue &#x1f5d1;️ 4. 移除元素&#xff1a;el.removeChild() &#x1…

CSS Day07

1.搭建项目目录 2.网页头部SEO三大标签 3.Favicon图标与版心 &#xff08;1&#xff09;Favicon图标 &#xff08;2&#xff09;版心 4.快捷导航 5.头部-布局 6.头部-logo 7.头部-导航 8.头部-搜索 9头部-购物车 10.底部-布局 11.底部-服务区域 12.底部-帮助中心 13.底部-版权…

RV1126-OPENCV 交叉编译

一.下载opencv-3.4.16.zip到自己想装的目录下 二.解压并且打开 opencv 目录 先用 unzip opencv-3.4.16.zip 来解压 opencv 的压缩包&#xff0c;并且进入 opencv 目录(cd opencv-3.4.16) 三. 修改 opencv 的 cmake 脚本的内容 先 cd platforms/linux 然后修改 arm-gnueabi.to…

【深度学习】 19. 生成模型:Diffusion Models

Diffusion Models Diffusion Models 简介 Diffusion 模型是一类通过逐步添加噪声并再逆向还原的方式进行图像生成的深度生成模型。其基本流程包括&#xff1a; 前向过程&#xff08;Forward Process&#xff09;&#xff1a;将真实图像逐步加噪&#xff0c;最终变为高斯噪声…

JMeter 直连数据库

1.直连数据库的使用场景 1.1 参数化&#xff0c;例如登录使用的账户名密码都可以从数据库中取得 1.2 断言&#xff0c;查看实际结果和数据库中的预期结果是否一致 1.3 清理垃圾数据&#xff0c;例如插入一个用户&#xff0c;它的ID不能相同&#xff0c;在测试插入功能后将数据删…

易路 iBuilder:解构企业 AI 落地困境,重构智能体时代生产力范式

一、从大模型到智能体的产业跃迁 2024 年堪称中国人工智能产业的 "战略拐点" 之年。当 DeepSeek R1 模型以 "技术 价格" 双重普惠模式掀起行业震荡时&#xff0c;各企业纷纷意识到&#xff0c;大模型的真正价值不在于技术炫技&#xff0c;而在于成为企业…

计算机网络之路由表更新

1.解题思路 对新接收到的路由表进行更新&#xff0c;全部"距离"1&#xff0c;且"下一跳路由器"都写成发送方路由器的名称。 开始对比新表和原来的路由表 1.看目的网络 如果是新的目的网络&#xff0c;则直接把对应的各项信息填入表中&#xff1b;如果是相同…