当前位置 : 首页 > 车辆数据

Spring Cloud Alibaba Sentinel 整合 Feign 实现服务熔断保护

<|begin▁of▁sentence|># 1. 概述 本文分享 **Spring Cloud Alibaba 之 Sentinel 与 Feign 的整合**。Sentinel 提供了对 Feign 的支持,让我们可以非常方便的在 Feign 调用时,使用 Sentinel 进行保护。 > 友情提示:对 Sentinel 基本概念不熟悉的胖友,可以阅读[《Sentinel 官方文档 —— 介绍》](https://github.com/alibaba/Sentinel/wiki/介绍)进行学习。考虑到胖友的英语水平,可以阅读[《Spring Cloud Alibaba 官方文档 —— 熔断器 Sentinel》](https://github.com/alibaba/spring-cloud-alibaba/wiki/Sentinel)的中文版本。 在开始本文之前,胖友需要对 Feign 进行简单的了解。可以阅读[《Spring Cloud 源码分析 —— Feign》](http://www.iocoder.cn/Spring-Cloud/Feign/?self)文章。 # 2. 如何集成 在 Spring Cloud Alibaba 中,Sentinel 和 Feign 的整合,通过 **spring-cloud-alibaba-sentinel** 来完成。那么,我们需要引入该依赖,如下图所示: ```xml org.springframework.cloud spring-cloud-starter-alibaba-sentinel ``` 同时,因为我们要使用 Feign 进行声明式 HTTP 调用,所以需要引入 **spring-cloud-starter-openfeign** 依赖,如下图所示: ```xml org.springframework.cloud spring-cloud-starter-openfeign ``` # 3. 快速入门 > 示例代码对应仓库: > > - 服务提供者:`labx-10-sc-sentinel-demo01-provider` > - 服务消费者:`labx-10-sc-sentinel-feign-demo01-consumer` 本小节,我们来搭建一个 Sentinel 整合 Feign 的示例。步骤如下: - 首先,搭建一个服务提供者 `demo-provider`,提供 HTTP 接口。 - 然后,搭建一个服务消费者 `demo-consumer`,使用 Feign 调用服务提供者 `demo-provider` 的 HTTP 接口。同时,引入 Sentinel 进行保护。 ## 3.1 搭建服务提供者 创建 [**labx-10-sc-sentinel-demo01-provider**](https://github.com/YunaiV/SpringBoot-Labs/tree/master/labx-10-spring-cloud-alibaba-sentinel/labx-10-sc-sentinel-demo01-provider) 项目,作为服务提供者 `demo-provider`。最终项目代码如下图所示:![ 项目](E:\Development\Typora\images\11-16544130969043.png) ### 3.1.1 引入依赖 创建 [`pom.xml`](https://github.com/YunaiV/SpringBoot-Labs/blob/master/labx-10-spring-cloud-alibaba-sentinel/labx-10-sc-sentinel-demo01-provider/pom.xml) 文件,引入 Spring Cloud、Spring Boot、Nacos Discovery 相关依赖。代码如下: ```xml labx-10 cn.iocoder.springboot.labs 1.0-SNAPSHOT 4.0.0 labx-10-sc-sentinel-demo01-provider org.springframework.boot spring-boot-starter-web com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery ```

栏目列表