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

article/2025/8/13 12:13:56

目录

    • 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: 8003spring:application:name: nacos-payment-servicecloud: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 {@Overridepublic 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: 9003spring:application:name: nacos-order-servicecloud: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 {@Resourceprivate 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: 9527spring:application:name: cloud-gatewaycloud:gateway:routes:- id: pay_routh1  # 路由的ID(类似mysql主键ID),没有固定规则但要求唯一,建议配合服务名uri: http://localhost:8003predicates:- 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();}@PostConstructpublic 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() {@Overridepublic 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.hkcw.cn/article/weZCVxeDkP.shtml

相关文章

远程管理SSH服务的搭建

一、搭建SSH服务 1、关闭防火墙与SELinux # 关闭firewalld防火墙 # 临时关闭 systemctl stop firewalld # 关闭开机自启动 systemctl disable firewalld# 关闭selinux # 临时关闭 setenforce 0 # 修改配置文件 永久关闭 vim /etc/selinux/config SELINUXdisabled2、配置yum源…

Cesium快速入门到精通系列教程二

一、添加地形与添加自定义地形 在 Cesium 1.93 中添加地形可以通过配置terrainProvider实现。Cesium 支持多种地形数据源&#xff0c;包括 Cesium Ion 提供的全球地形、自定义地形服务以及开源地形数据。下面介绍几种常见的添加地形的方法&#xff1a; 使用 Cesium Ion 全球地…

基于FashionMnist数据集的自监督学习(生成式自监督学习VAE算法)

目录 一&#xff0c;VAE 1.1 VAE的简介 1.2 VAE的核心思想 1.3 VAE的结构 1.4 VAE的工作原理 1.5 VAE 与传统自动编码器&#xff08;AE&#xff09;的区别 1.6 VAE 的应用场景 二&#xff0c;代码逻辑分析 2.1 整体逻辑 2.2 VAE模型 2.3 训练策略与优化 2.4 自适应学…

ESP32基础知识1:项目工程建立和烧录

ESP32基础知识1&#xff1a;项目工程建立和烧录 一、本文内容与前置知识点1. 本文内容2. 前置知识点 二、新建工程1. 工程配置2. 依照模板建立项目 三、硬件烧录1. 硬件准备2. 烧录器和ESP32连接3. 电脑端设置4. 烧录成功演示 四、参考文献 一、本文内容与前置知识点 1. 本文内…

duilib图片属性中corner属性九宫格拉伸说明

在duilib中&#xff0c;图片设置里有corner属性&#xff0c;类似于android系统里的九宫格&#xff0c;对应的分区域拉伸被称为九宫格拉伸。设置corner属性后&#xff0c;将区域分成3x3的九个区域&#xff0c;如下所示&#xff1a; 除了4个拐角区域不拉伸&#xff0c;其余5个区域…

《操作系统真相还原》——进入内核

ELF 按书上的操作来&#xff0c;在现代操作平台编译链接默认生成elf64 格式的文件&#xff0c; 很显然程序头位置发生变化&#xff0c;因为定义elf 结构的类型中有64位&#xff0c;所以我们需要将编译链接出32位格式的 gcc -m32 -c -o main.o main.c ld -m elf_i386 main.o …

笔试笔记(运维)

&#xff08;数据库&#xff0c;SQL&#xff09; limit1 随机返回其中一个聚合函数不可以嵌套使用 【^】这个里面的数据任何形式组合都没有 sql常用语句顺序&#xff1a;from-->where-->group by-->having-->select-->order by-->limit 只要其中一个表存在匹…

医疗数理范式化:从范式迁移到认知革命的深度解析

引言 在当代医疗领域,数理思维已经从辅助工具逐渐发展成为核心决策支持系统的关键组成部分。随着数字技术的迅猛发展,医疗行业正经历着前所未有的变革,而数理思维作为这一变革的核心驱动力,正在深刻重塑医疗实践的方方面面。数理思维在医疗领域的应用,本质上是将抽象的数…

golang -- slice 底层逻辑

目录 一、前言二、结构三、创建3.1 根据 make创建3.2 通过数组创建 四、内置append追加元素4.1 追加元素4.2 是否扩容4.2.1 不扩容4.2.2 扩容 总结 一、前言 前段时间学了go语言基础&#xff0c;过了一遍之后还是差很多&#xff0c;所以又结合几篇不同资料重新学习了一下相关…

Fashion-MNIST LeNet训练

前面使用线性神经网络softmax 和 多层感知机进行图像分类&#xff0c;本次我们使用LeNet 卷积神经网络进行 训练&#xff0c;期望能捕捉到图像中的图像结构信息&#xff0c;提高识别精度&#xff1a; import torch import torchvision from torchvision import transforms f…

数据库系统概论(十)SQL 嵌套查询 超详细讲解(附带例题表格对比带你一步步掌握)

数据库系统概论&#xff08;十&#xff09;SQL 嵌套查询 超详细讲解&#xff08;附带例题表格对比带你一步步掌握&#xff09; 前言一、什么是嵌套查询&#xff1f;1. 基础组成&#xff1a;查询块2. 嵌套的两种常见位置&#xff08;1&#xff09;藏在 FROM 子句里&#xff08;当…

Azure 机器学习初学者指南

Azure 机器学习初学者指南 在我们的初学者指南中探索Azure机器学习&#xff0c;了解如何设置、部署模型以及在Azure生态系统中使用AutoML & ML Studio。Azure 机器学习 &#xff08;Azure ML&#xff09; 是一项全面的云服务&#xff0c;专为机器学习项目生命周期而设计&am…

使用win11圆角指针教程

一.准备文件 win11圆角指针下载链接&#xff1a;https://wwxh.lanzoum.com/iwsZH2xqmy0d 密码&#xff1a;em 二.开始安装 1.将下载的压缩包解压&#xff08;随便存哪&#xff0c;最后可以删掉&#xff09; 右键&#xff0c;点击“全部解压缩” 点击“提取” 2.安装 选…

day16 leetcode-hot100-30(链表9)

24. 两两交换链表中的节点 - 力扣&#xff08;LeetCode&#xff09; 1.模拟法 思路 模拟题目要求进行两两交换&#xff0c;但有一点需要注意&#xff0c;比如交换3与4后&#xff0c;1仍然指的是3&#xff0c;这是不正确的&#xff0c;所以1指针的next也需要修改&#xff0c;所…

C语言进阶--程序的编译(预处理动作)+链接

1.程序的翻译环境和执行环境 在ANSI C标准的任何一种实现中&#xff0c;存在两种不同的环境。 第一种是翻译环境&#xff1a;将源代码转换为可执行的机器指令&#xff08;0/1&#xff09;; 第二种是执行环境&#xff1a;用于实际执行代码。 2.详解编译链接 2.1翻译环境 程…

GCA解码大脑因果网络

格兰杰因果分析&#xff08;Granger Causality Analysis,GCA&#xff09; 是一种测量脑区之间有效性连接&#xff08;effective connectivity&#xff09;的成熟方法。利用多元线性回归分析一个时间序列的过去值是否能正确预测另一个时间序列的当前值&#xff0c;可以用来描述脑…

H5S 大华SDK带图报警类型及热成像报警支持

目前很多应用都希望报警带对应的图片&#xff0c;比如控制中心在弹报警框的时候需要有一张图片让人工更快的做出判断&#xff0c;下面介绍使用大华SDK 的带图报警功能。 大华SDK支持接入设备带图报警&#xff0c;并且支持热成像通道报警&#xff0c;设置订阅事件并吧协议端口设…

(javaSE)Java数组进阶:数组初始化 数组访问 数组中的jvm 空指针异常

数组的基础 什么是数组呢? 数组指的是一种容器,可以用来存储同种数据类型的多个值 数组的初始化 初始化&#xff1a;就是在内存中,为数组容器开辟空间,并将数据存入容器中的过程。 数组初始化的两种方式&#xff1a;静态初始化&#xff0c;动态初始化 数组的静态初始化 初始化…

Java数据结构——八大排序

排序 插⼊排序希尔排序直接选择排序堆排序冒泡排序快速排序归并排序计数排序 排序的概念 排序&#xff1a;就是将一串东西&#xff0c;按照要求进行排序&#xff0c;按照递增或递减排序起来 稳定性&#xff1a;就是比如排序中有两个相同的数&#xff0c;如果排序后&#xff0c…

【Linux】Linux文件系统详解

目录 Linux系统简介 Linux常见发行版&#xff1a; Linux/windows文件系统区别 Linux文件系统各个目录用途 Linux系统核心文件 系统核心配置文件 用户与环境配置文件 系统运行与日志文件 Linux文件名颜色含义 Linux文件关键信息解析 &#x1f525;个人主页 &#x1f52…