Sentinel服务熔断功能(sentinel整合ribbon+openFeign+fallback)

article/2025/9/21 0:26:16

目录

1、Sentinel服务熔断功能

        一、Ribbon系列

        (一)提供者9003/9004

        (二)消费者84 

        二、OpenFeign系列

        三、熔断框架比较

2、规则持久化


1、Sentinel服务熔断功能

一、Ribbon系列

(一)提供者9003/9004

新建cloudalibaba-provider-payment9003/9004两个一样的做法

Pom

<dependencies><!--SpringCloud ailibaba nacos --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity --><groupId>com.atguigu.springcloud</groupId><artifactId>cloud-api-commons</artifactId><version>${project.version}</version></dependency><!-- SpringBoot整合Web组件 --><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><!--日常通用jar包配置--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>

YML

server:port: 9003 #9004spring:application:name: nacos-payment-providercloud:nacos:discovery:server-addr: localhost:8848 #配置Nacos地址management:endpoints:web:exposure:include: '*'

 主启动

@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain9003
{public static void main(String[] args) {SpringApplication.run(PaymentMain9003.class, args);}
}

业务类

@RestController
public class PaymentController
{@Value("${server.port}")private String serverPort;public static HashMap<Long,Payment> hashMap = new HashMap<>();static{hashMap.put(1L,new Payment(1L,"28a8c1e3bc2742d8848569891fb42181"));hashMap.put(2L,new Payment(2L,"bba8c1e3bc2742d8848569891ac32182"));hashMap.put(3L,new Payment(3L,"6ua8c1e3bc2742d8848569891xt92183"));}@GetMapping(value = "/paymentSQL/{id}")public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id){Payment payment = hashMap.get(id);CommonResult<Payment> result = new CommonResult(200,"from mysql,serverPort:  "+serverPort,payment);return result;}}

 测试地址:http://localhost:9003/paymentSQL/1

(二)消费者84 

新建cloudalibaba-consumer-nacos-order84

POM

<dependencies><!--SpringCloud ailibaba nacos --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><!--SpringCloud ailibaba sentinel --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId></dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity --><dependency><groupId>com.atguigu.springcloud</groupId><artifactId>cloud-api-commons</artifactId><version>${project.version}</version></dependency><!-- SpringBoot整合Web组件 --><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><!--日常通用jar包配置--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>

YML

server:port: 84spring:application:name: nacos-order-consumercloud:nacos:discovery:server-addr: localhost:8848sentinel:transport:#配置Sentinel dashboard地址dashboard: localhost:8080#默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口port: 8719#消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者)
service-url:nacos-user-service: http://nacos-payment-provider

主启动

@EnableDiscoveryClient
@SpringBootApplication
public class OrderNacosMain84
{public static void main(String[] args) {SpringApplication.run(OrderNacosMain84.class, args);}
}

 业务类

ApplicationContextConfig

@Configuration
public class ApplicationContextConfig
{@Bean@LoadBalancedpublic RestTemplate getRestTemplate(){return new RestTemplate();}
}

CircleBreakerController 

@RestController
@Slf4j
public class CircleBreakerController
{public static final String SERVICE_URL = "http://nacos-payment-provider";@Resourceprivate RestTemplate restTemplate;@RequestMapping("/consumer/fallback/{id}")@SentinelResource(value = "fallback") public CommonResult<Payment> fallback(@PathVariable Long id){CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);if (id == 4) {throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");}else if (result.getData() == null) {throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");}return result;}
}

 

只配置fallback

    @RequestMapping("/consumer/fallback/{id}")@SentinelResource(value = "fallback", fallback = "handlerFallback")public CommonResult<Payment> fallback(@PathVariable Long id){CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);if (id == 4) {throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");}else if (result.getData() == null) {throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");}return result;}public CommonResult handlerFallback(@PathVariable  Long id,Throwable e) {Payment payment = new Payment(id,"null");return new CommonResult<>(444,"兜底异常handlerFallback,exception内容  "+e.getMessage(),payment);}

如果在自定义的异常之前就出现了异常,那么输出的就会是那个异常

 只配置blockhandler

    @RequestMapping("/consumer/fallback/{id}")
//    @SentinelResource(value = "fallback", fallback = "handlerFallback")@SentinelResource(value = "fallback", blockHandler = "blockHandler")public CommonResult<Payment> fallback(@PathVariable Long id){CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);if (id == 4) {throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");}else if (result.getData() == null) {throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");}return result;}public CommonResult blockHandler(@PathVariable  Long id, BlockException blockException) {Payment payment = new Payment(id,"null");return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException  "+blockException.getMessage(),payment);}

异常超过2次后,断路器打开,断电跳闸,系统被保护 

 配置fallback和blockhandler

    @RequestMapping("/consumer/fallback/{id}")
//    @SentinelResource(value = "fallback", fallback = "handlerFallback")
//    @SentinelResource(value = "fallback", blockHandler = "blockHandler")@SentinelResource(value = "fallback", fallback = "handlerFallback",blockHandler = "blockHandler")public CommonResult<Payment> fallback(@PathVariable Long id){CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);if (id == 4) {throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");}else if (result.getData() == null) {throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");}return result;}public CommonResult blockHandler(@PathVariable  Long id, BlockException blockException) {Payment payment = new Payment(id,"null");return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException  "+blockException.getMessage(),payment);}public CommonResult handlerFallback(@PathVariable  Long id,Throwable e) {Payment payment = new Payment(id,"null");return new CommonResult<>(444,"兜底异常handlerFallback,exception内容  "+e.getMessage(),payment);}

如果次数没有超过sentinel配置的流控规则的时候出现异常,那么是调用了fallback方法。

当超过次数后无论是否出现异常,都是调用blockhandler。

二、OpenFeign系列

修改84模块,Feign组件一般是用于消费侧

POM文件添加依赖

    <!--SpringCloud openfeign --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency>

激活Sentinel对Feign的支持

# 激活Sentinel对Feign的支持
feign:sentinel:enabled: true 

 带@FeignClient注解的业务接口

@FeignClient(value = "nacos-payment-provider",fallback = PaymentFallbackService.class)//调用中关闭9003服务提供者
public interface PaymentService
{@GetMapping(value = "/paymentSQL/{id}")public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id);
}

PaymentFallbackService

@Component
public class PaymentFallbackService implements PaymentService
{@Overridepublic CommonResult<Payment> paymentSQL(Long id){return new CommonResult<>(444,"服务降级返回,没有该流水信息",new Payment(id, "errorSerial......"));}
}

 Controller

    //==================OpenFeign@Resourceprivate PaymentService paymentService;@GetMapping(value = "/consumer/openfeign/{id}")public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id){if(id == 4){throw new RuntimeException("没有该id");}return paymentService.paymentSQL(id);}

主启动类上添加@EnableFeignClients

 测试84调用9003,此时故意关闭9003微服务提供者,看84消费侧自动降级,不会被耗死

 

 三、熔断框架比较

 

2、规则持久化

一旦我们重启应用,sentinel规则将消失,生产环境需要将配置规则进行持久化

将限流配置规则持久化进Nacos保存,只要刷新8401某个rest地址,sentinel控制台
的流控规则就能看到,只要Nacos里面的配置不删除,针对8401上sentinel上的流控规则持续有效

修改cloudalibaba-sentinel-service8401

POM文件添加依赖

<!--SpringCloud ailibaba sentinel-datasource-nacos -->
<dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-datasource-nacos</artifactId>
</dependency>

YML

server:port: 8401spring:application:name: cloudalibaba-sentinel-servicecloud:nacos:discovery:server-addr: localhost:8848 #Nacos服务注册中心地址sentinel:transport:dashboard: localhost:8080 #配置Sentinel dashboard地址port: 8719datasource:ds1:nacos:server-addr: localhost:8848dataId: cloudalibaba-sentinel-servicegroupId: DEFAULT_GROUPdata-type: jsonrule-type: flowmanagement:endpoints:web:exposure:include: '*'feign:sentinel:enabled: true # 激活Sentinel对Feign的支持

即添加了添加Nacos数据源配置

spring:cloud:sentinel:datasource:ds1:nacos:server-addr: localhost:8848dataId: ${spring.application.name}groupId: DEFAULT_GROUPdata-type: jsonrule-type: flow

添加Nacos业务规则配置

 

[{"resource": "/rateLimit/byUrl","limitApp": "default","grade": 1,"count": 1,"strategy": 0,"controlBehavior": 0,"clusterMode": false}
]
resource:资源名称;
limitApp:来源应用;
grade:阈值类型,0表示线程数,1表示QPS;
count:单机阈值;
strategy:流控模式,0表示直接,1表示关联,2表示链路;
controlBehavior:流控效果,0表示快速失败,1表示Warm Up,2表示排队等待;
clusterMode:是否集群。

此时停止8401服务后再次启动后就能看到流控规则了,但可能需要先访问几次网址,流控规则才会出现在sentinel控制台


http://chatgpt.dhexx.cn/article/nlGZk491.shtml

相关文章

Sentinel的blockHandler与fallback的区别

一、两者区别 这里说明一下&#xff0c;笔者使用的是Alibaba的Sentinel限流降级框架&#xff0c;Sentinel提供了限流、服务降级功能&#xff0c;但是只是限制后&#xff0c;返回不可控的结果肯定是不行的&#xff0c;我们还要保证调用者在调用那些被限制的服务时候&#xff0c…

Fallback函数

Fallback函数的使用 特点&#xff1a; 1.无名字&#xff0c;无参数&#xff0c;无返回值 2.如果请求的方法在合约中不存在&#xff0c;则会调用fallback函数 3.对合约转账的时候&#xff0c;会自动执行fallback函数(可能会产生Reentrancy漏洞) 4.在高版本中已经将定义形式改为…

sentinel1.8.1中fallback兜底方法和@RestControllerAdvice全局异常处理

环境描述&#xff0c;同上一篇文章 sentinel设置blockHandlerClass和blockHandler不生效的坑 目录 1.sentinel的blockHandler和fallback 2.RestControllerAdvice是否也可以兜底&#xff1f;&#xff1f;&#xff1f; 总结&#xff1a;二者结果相似&#xff0c;按需自取即…

Spring Cloud Alibaba(四)简单接入Sentinel(fallback用法)

SentinelResource 注解 接着 Spring Cloud Alibaba&#xff08;三&#xff09;简单接入Sentinel&#xff08;Sentinel 控制台&#xff09;&#xff0c;来看一下 SentinelResource 一些常用的属性&#xff1a; value &#xff1a; 资源名称&#xff0c;必需项&#xff08;不能为…

【mysql】sql优化常用的几种方法,19种最有效的sql优化技巧(转载)

前言 转载 有哪些方法 转载自&#xff1a;https://www.changchenghao.cn/n/174426.html EXPLAIN 做MySQL优化&#xff0c;我们要善用EXPLAIN查看SQL执行计划。 下面来个简单的示例&#xff0c;标注&#xff08;1、2、3、4、5&#xff09;我们要重点关注的数据&#xff1a; typ…

SQL查询优化技巧

查询优化的本质是让数据库优化器为SQL语句选择最佳的执行计划。一般来说&#xff0c;对于在线交易处理&#xff08;OLTP&#xff09;系统的数据库&#xff0c;减少数据库磁盘I/O是SQL语句性能优化的首要方法&#xff0c;因为磁盘访问通常是数据库性能的瓶颈所在。 另外&#xf…

SQL语句优化有哪些方法

1.如何定位慢查询? mysql默认慢查询为10秒,如果超过10秒,没有数据返回则为慢查询. 当我们通过安全日志启动时,当超过超时时间时,会将超时的SQl存放在日志中,我们去分析这些sql然后进行调优. 2.数据库设计要合理 什么是数据库设计? 主要就是三范式 1p原子性:每列不可再分…

MySQL的SQL优化常用30种方法

1、对查询进行优化&#xff0c;应尽量避免全表扫描&#xff0c;首先应考虑在 where 及 order by 涉及的列上建立索引。 &#xff08;1&#xff09;未建立索引前&#xff0c;执行计划是全表扫描&#xff1a; &#xff08;2&#xff09;建立索引后&#xff0c;走索引查询&…

常用SQL优化方法

个人博客请访问 http://www.x0100.top 1、应尽量避免在 where 子句中使用!或<>操作符&#xff0c;否则将引擎放弃使用索引而进行全表扫描。 2、对查询进行优化&#xff0c;应尽量避免全表扫描&#xff0c;首先应考虑在 where 及 order by 涉及的列上建立索引。 3、应…

Mysql的sql优化方法

1、选择最合适的字段属性 Mysql是一种关系型数据库&#xff0c;可以很好地支持大数据量的存储&#xff0c;但是一般来说&#xff0c;数据库中的表越小&#xff0c;在它上面执行的查询也就越快。因此&#xff0c;在创建表的时候&#xff0c;为了获得更好的性能&#xff0c;我们可…

sql优化常用的几种方法,19种最有效的sql优化技巧

sql优化常用的几种方法&#xff0c;19种最有效的sql优化技巧 本文我们来谈谈项目中常用的MySQL优化方法&#xff0c;共19条&#xff0c;具体如下&#xff1a; 1、EXPLAIN 做MySQL优化&#xff0c;我们要善用EXPLAIN查看SQL执行计划。 下面来个简单的示例&#xff0c;标注&am…

15个常用的sql优化技巧

原文&#xff1a;https://www.cnblogs.com/12lisu/p/15535940.html 作者&#xff1a;苏三说技术 前言 sql优化是一个大家都比较关注的热门话题&#xff0c;无论你在面试&#xff0c;还是工作中&#xff0c;都很有可能会遇到。 如果某天你负责的某个线上接口&#xff0c;出现…

TiDB数据库要点及练习

TiDB Server 处理客户端的连接 SQL语句的解析和编译 关系数据库与KV的转化 SQL语句的执行 执行oline DDL 垃圾回收 热点小表缓存V6.0 TiKV 数据持久化 副本的强一致性和高可用性 MVCC&#xff08;多版本并发控制&#xff09; 分布式事务支持 Coprocessor&#xff0…

【TIDB】TIDB数据类型详解

TIDB的数据类型 文章目录 TIDB的数据类型1 数值类型2 日期和时间类型3 字符串类型3 SET 类型4 JSON类型 1 数值类型 1 整数类型 2 浮点类型 3 定点类型 decamal(20,6) 2 日期和时间类型 3 字符串类型 1 CHAR 类型 定长字符串。CHAR 列的长度固定为创建表时声明的长度。当保…

TiDB 的现在和未来

本文根据黄东旭在 PingCAP D 轮融资线上发布会的演讲实录进行整理。 TiDB 的现在和未来 大家好&#xff0c;我是黄东旭&#xff0c;是 PingCAP 的联合创始人和 CTO&#xff0c;这是 PingCAP 成立以来的第一次发布会&#xff0c;我想跟大家简单聊聊 TiDB 在产品和技术上的更新。…

TiDB Cloud

TiDB Cloud 为什么选择TiDB 分布式数据库-多租户混合工作负载-在同一个数据库中 事务型&#xff1a;基于行的数据分析型&#xff1a;基于列的数据 弹性比例&#xff1a; 缩小-减少节点横向扩展-添加节点 基于“RAFT”的高可用性 每个数据段的3个可用区进行复制 多租户 什么…

TiDB整体架构详解、TiDB核心特性——水平扩展、高可用

TiDB 集群主要包括三个核心组件&#xff1a;TiDB Server&#xff0c;PD Server 和 TiKV Server。此外&#xff0c;还有用于解决用户复杂 OLAP 需求的 TiSpark 组件和简化云上部署管理的 TiDB Operator 组件。 架构图解 TiDB Server TiDB Server 负责接收 SQL 请求&#xff0c…

TiDB(2):TiDB架构特性

1 TiDB 整体架构 TiDB 集群主要包括三个核心组件&#xff1a;TiDB Server&#xff0c;PD Server 和 TiKV Server。此外&#xff0c;还有用于解决用户复杂 OLAP 需求的 TiSpark 组件和简化云上部署管理的 TiDB Operator 组件。 架构图解 1.1 TiDB Server TiDB Server 负责接收…

TiDB使用总结

使用场景 TiDB 是 PingCAP 公司自主设计、研发的开源分布式关系型数据库&#xff0c;是一款同时支持在线事务处理(OLTP)与在线分析处理 (HTAP) 的融合型分布式数据库产品&#xff0c;具备水平扩容或者缩容、金融级高可用、实时 HTAP、云原生的分布式数据库、兼容 MySQL 5.7 协…

猿创征文|分布式国产数据库 TiDB 从入门到实战

写在前面 本文讲解的是目前欢迎程度最高分布式国产数据库 TiDB&#xff0c;详细讲解了 TiDB 的由来、架构、SQL 基本操作、SpringBoot 整合 TiDB 等内容。 目录 写在前面一、概述二、与 MySQL 兼容性对比三、安装使用四、SQL 基本操作4.1、库操作4.2、表操作4.3、索引操作4.4、…