example: update sentinel example (#3709)

Signed-off-by: yuluo-yx <yuluo08290126@gmail.com>
pull/3796/head
YuLuo 7 months ago committed by GitHub
parent d0da90c0db
commit 058496d625
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -141,6 +141,6 @@ If you are interested or want to go deeper, you are welcome to study the individ
- Nacos examples
- [Nacos config example](../../../nacos-example/readme.md)
- [Nacos discovery example](../../../nacos-example/readme.md)
- [Sentinel core example](../../../sentinel-example/sentinel-core-example/readme.md)
- [Sentinel core example](../../../sentinel-example/README.md)
- [Seata example](../../../seata-example/readme.md)
- [RocketMQ example](../../../rocketmq-example/readme.md)

@ -119,6 +119,6 @@ Of course, there is more to each component than just what is demonstrated in the
- Nacos examples
- [Nacos config example](../../../nacos-example/readme.md)
- [Nacos discovery example](../../../nacos-example/readme.md)
- [Sentinel core example](../../../sentinel-example/sentinel-core-example/readme.md)
- [Sentinel core example](../../../sentinel-example/README.md)
- [Seata example](../../../seata-example/readme.md)
- [RocketMQ example](../../../rocketmq-example/readme.md)

@ -207,6 +207,6 @@ If you are interested or want to go deeper, you are welcome to study the individ
- Nacos examples
- [Nacos config example](../../../nacos-example/readme.md)
- [Nacos discovery example](../../../nacos-example/readme.md)
- [Sentinel core example](../../../sentinel-example/sentinel-core-example/readme.md)
- [Sentinel core example](../../../sentinel-example/README.md)
- [Seata example](../../../seata-example/readme.md)
- [RocketMQ example](../../../rocketmq-example/readme.md)

@ -140,9 +140,8 @@ docker-compose-env.yml 文件运行成功之后,添加 Nacos 配置:
当然各个组件的功能特性不仅仅只包含最佳实践中演示的这些,如果您感兴趣或是想要深入了解,欢迎学习各个组件的独立 example 相关文档。
- Nacos examples
- [Nacos config example](../../../nacos-example/readme-zh.md)
- [Nacos discovery example](../../../nacos-example/readme-zh.md)
- [Sentinel core example](../../../sentinel-example/sentinel-core-example/readme-zh.md)
- [Seata example](../../../seata-example/readme-zh.md)
- [RocketMQ example](../../../rocketmq-example/readme-zh.md)
- [Nacos config example](../../../nacos-example/readme.md)
- [Nacos discovery example](../../../nacos-example/readme.md)
- [Sentinel core example](../../../sentinel-example/README-zh.md)
- [Seata example](../../../seata-example/readme.md)
- [RocketMQ example](../../../rocketmq-example/readme.md)

@ -119,8 +119,9 @@ helm uninstall integrated-example
当然各个组件的功能特性不仅仅只包含最佳实践中演示的这些如果您对SCA感兴趣或是想要深入了解SCA项目欢迎阅览各个组件的独立 example 相关文档。
- Nacos examples
- [Nacos config example](../../../nacos-example/readme-zh.md)
- [Nacos discovery example](../../../nacos-example/readme-zh.md)
- [Sentinel core example](../../../sentinel-example/sentinel-core-example/readme-zh.md)
- [Seata example](../../../seata-example/readme-zh.md)
- [RocketMQ example](../../../rocketmq-example/readme-zh.md)
- [Nacos config example](../../../nacos-example/readme.md)
- [Nacos discovery example](../../../nacos-example/readme.md)
- [Sentinel core example](../../../sentinel-example/README-zh.md)
- [Seata example](../../../seata-example/readme.md)
- [RocketMQ example](../../../rocketmq-example/readme.md)
-

@ -204,8 +204,9 @@ sh bin/mqbroker
当然各个组件的功能特性不仅仅只包含最佳实践中演示的这些,如果您感兴趣或是想要深入了解,欢迎学习各个组件的独立 example 相关文档。
- Nacos examples
- [Nacos config example](../../../nacos-example/readme-zh.md)
- [Nacos discovery example](../../../nacos-example/readme-zh.md)
- [Sentinel core example](../../../sentinel-example/sentinel-core-example/readme-zh.md)
- [Seata example](../../../seata-example/readme-zh.md)
- [RocketMQ example](../../../rocketmq-example/readme-zh.md)
- [Nacos config example](../../../nacos-example/readme.md)
- [Nacos discovery example](../../../nacos-example/readme.md)
- [Sentinel core example](../../../sentinel-example/README-zh.md)
- [Seata example](../../../seata-example/readme.md)
- [RocketMQ example](../../../rocketmq-example/readme.md)
-

@ -0,0 +1,319 @@
# Spring Cloud Alibaba Sentinel Example
## 项目说明
本 Example 项目演示如何使用 `spring-cloud-starter-alibaba-sentinel` 完成 Spring Cloud 应用中的流量治理功能。
[Sentinel](https://github.com/alibaba/Sentinel) 是阿里巴巴开源的分布式系统的流量防卫组件Sentinel 以流量作为切入点,从流量控制,熔断降级,系统负载保护等多个维度保护服务的稳定性。
## Sentinel Example
在本 Example 项目中,主要演示 Sentinel 断路器,整合 Spring Cloud Gateway 和 OpenFeign、RestTemplate 以及 Webclient 的使用。
### 下载并启动 Sentinel Console
1. 首先需要获取 Sentinel 控制台Sentinel Console 支持直接下载和源码构建两种方式
1. 直接下载:[下载 Sentinel 控制台](https://github.com/alibaba/Sentinel/releases)
2. 源码构建:进入 Sentinel [Github 项目页面](https://github.com/alibaba/Sentinel),将代码 clone 到本地自行编译打包,[参考此文档](https://github.com/alibaba/Sentinel/blob/1.8/sentinel-dashboard/README.md)。
2. 启动控制台,执行 Java 命令 `java -jar sentinel-dashboard.jar` 完成 Sentinel 控制台的启动。
控制台默认的监听端口为 `8080`。Sentinel 控制台使用 Spring Boot 编程模型开发,如果需要指定其他端口,请使用 Spring Boot 容器配置的标准方式,详情请参考 [Spring Boot 文档](https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-customizing-embedded-containers)。
### Sentinel Core Example
在此 Example 模块中,主要演示如何使用 Sentinel 的基本功能完成 Spring Cloud 应用的流量管控。 在启动 Example 进行演示之前,先了解一下如何在 Spring Cloud 应用中接入 Sentinel 组件。
#### 项目编写
> **注意:本文档只是为了便于理解接入方式。本示例代码中已经完成接入工作,您无需再进行修改。**
1. 首先,修改 `pom.xml` 文件,引入 Sentinel starter。
```xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
```
2. 接入限流埋点
- HTTP 埋点
`spring-cloud-starter-alibaba-sentinel` 默认为所有的 HTTP 服务提供了限流埋点,如果只想对 HTTP 服务进行限流,那么只需要引入依赖,无需修改代码。
- 自定义埋点
如果需要对某个特定的方法进行限流或降级,可以通过 `@SentinelResource` 注解来完成限流的埋点,示例代码如下:
```java
@SentinelResource("resource")
public String hello() {
return "Hello";
}
```
当然也可以通过原始的 `SphU.entry(xxx)` 方法进行埋点,可以参见 [Sentinel 文档](https://github.com/alibaba/Sentinel/wiki/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8#%E5%AE%9A%E4%B9%89%E8%B5%84%E6%BA%90)。
3. 配置限流规则
Sentinel 提供了两种配置限流规则的方式:代码配置 和 控制台配置。本示例使用的方式为通过代码配置。
1. 通过代码来实现限流规则的配置。一个简单的限流规则配置示例代码如下,更多限流规则配置详情请参考 [Sentinel 文档](https://github.com/alibaba/Sentinel/wiki/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8#%E5%AE%9A%E4%B9%89%E8%A7%84%E5%88%99)。
```java
List<FlowRule> rules = new ArrayList<FlowRule>();
FlowRule rule = new FlowRule();
rule.setResource(str);
// set limit qps to 10
rule.setCount(10);
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setLimitApp("default");
rules.add(rule);
FlowRuleManager.loadRules(rules);
```
2. 通过控制台进行限流规则配置请参考文章后面的图文说明。
#### 应用启动
1. 增加配置,在应用的 `/src/main/resources/application.yml` 中添加基本配置信息
```yaml
server:
port: 18083
spring:
application:
name: sentinel-core-example
cloud:
sentinel:
transport:
dashboard: localhost:8080
```
2. 启动应用,支持 IDE 直接启动和编译打包后启动。
1. IDE直接启动找到主类 `SentinelCoreApplication`,执行 main 方法启动应用。
2. 打包编译后启动:首先执行 `mvn clean package` 将工程编译打包,然后执行 `java -jar sentinel-core-example.jar` 启动应用。
#### 调用服务验证
使用 curl 命令分别调用两个 URL可以看到访问成功。
```shell
$ curl http://localhost:18083/test
Blocked by Sentinel (flow limiting)
$ curl http://localhost:18083/hello
Hello
```
#### 配置限流规则并验证
1. 访问 http://localhost:8080 页面,进行登陆,默认用户名和密码均为:`sentinel`。
可以在左侧看到 `sentinel-core-example` 应用已经注册到了控制台,单击 **流控规则** ,可以看到目前的流控规则为空。
> **注意:如果您在控制台没有找到应用,请调用一下进行了 Sentinel 埋点的 URL 或方法,因为 Sentinel 使用了 lazy load 策略。详细的排查过程请参见 [Sentinel FAQ](https://github.com/alibaba/Sentinel/wiki/FAQ)。**
<img src="./images/image-20240428171413303.png" alt="image-20240428171413303" style="zoom:50%;" />
2. 配置 URL 限流规则:点击新增流控规则,资源名填写需要限流的 URL 相对路径,单机阈值选择需要限流的阈值,点击新增进行确认。(为了便于演示效果,这里将值设置成了 1)。
<img src="./images/image-20240428171245517.png" alt="image-20240428171245517" style="zoom: 50%;" />
3. 配置自定义限流规则:点击新增流控规则,资源名填写 `@SentinelResource` 注解 `value` 字段的值,单机阈值选择需要限流的阈值,点击新增进行确认。(为了便于演示效果,这里将值设置成了 1)。
<img src="./images/image-20240428171608519.png" alt="image-20240428171608519" style="zoom:50%;" />
4. 访问 URL当 QPS 超过 1 时,可以看到限流效果如下。
![image-20240428171907705](./images/image-20240428171907705.png)
#### 自定义限流处理逻辑
* 默认限流异常处理
URL 限流触发后默认处理逻辑是,直接返回 "Blocked by Sentinel (flow limiting)"。 如果需要自定义处理逻辑,实现的方式如下:
```java
public class CustomUrlBlockHandler implements UrlBlockHandler {
@Override
public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
// todo add your logic
}
}
WebCallbackManager.setUrlBlockHandler(new CustomUrlBlockHandler());
```
* 使用 `@SentinelResource` 注解下的限流异常处理
如果需要自定义处理逻辑,填写 `@SentinelResource` 注解的 `blockHandler` 属性(针对所有类型的 `BlockException`,需自行判断)或 `fallback` 属性(针对熔断降级异常),注意**对应方法的签名和位置有限制**,详情见 [Sentinel 注解支持文档](https://github.com/alibaba/Sentinel/wiki/%E6%B3%A8%E8%A7%A3%E6%94%AF%E6%8C%81#sentinelresource-%E6%B3%A8%E8%A7%A3)。示例实现如下:
```java
public class TestService {
// blockHandler 是位于 ExceptionUtil 类下的 handleException 静态方法,需符合对应的类型限制.
@SentinelResource(value = "test", blockHandler = "handleException", blockHandlerClass = {ExceptionUtil.class})
public void test() {
System.out.println("Test");
}
// blockHandler 是位于当前类下的 exceptionHandler 方法,需符合对应的类型限制.
@SentinelResource(value = "hello", blockHandler = "exceptionHandler")
public String hello(long s) {
return String.format("Hello at %d", s);
}
public String exceptionHandler(long s, BlockException ex) {
// Do some log here.
ex.printStackTrace();
return "Oops, error occurred at " + s;
}
}
public final class ExceptionUtil {
public static void handleException(BlockException ex) {
System.out.println("Oops: " + ex.getClass().getCanonicalName());
}
}
```
一个简单的 `@SentinelResource` 示例可以见 [sentinel-demo-annotation-spring-aop](https://github.com/alibaba/Sentinel/tree/2021.x/sentinel-demo/sentinel-demo-annotation-spring-aop)。
### Sentinel Circuitbreaker Example
本 Example 主要演示 OpenFeign 整合 Sentinel 断路器的使用。
#### 准备配置文件
1. 添加配置到配置中心。dataId 为 `sentinel-circuitbreaker-rules.yml`
```yml
feign:
circuitbreaker:
enabled: true # 开启 feign 断路器支持
sentinel:
default-rule: default # 默认规则名称
rules:
# 默认规则, 对所有 feign client 生效
default:
- grade: 2 # 根据异常数目降级
count: 1
timeWindow: 15 # 降级后到半开状态的时间
statIntervalMs: 1000
minRequestAmount: 1
# 只对 feign client user 生效
user:
- grade: 2
count: 1
timeWindow: 15
statIntervalMs: 1000
minRequestAmount: 1
# 只对 feign client user 的方法 feignMethod 生效
# 括号里是参数类型, 多个逗号分割, 比如 user#method(boolean,String,Map)
"[user#feignMethod(boolean)]":
- grade: 2
count: 1
timeWindow: 10
statIntervalMs: 1000
minRequestAmount: 1
```
#### 验证配置生效
启动项目主类 `FeignCircuitBreakerApplication`
##### 验证默认 Feign client 生效
先访问 http://localhost/test/default/false 2 次 1秒内
再访问 http://localhost/test/default/true 断路器处于打开状态
##### 验证指定 Feign client 生效
先访问 http://localhost/test/feign/false 2 次 1秒内
再访问 http://localhost/test/feign/true 断路器处于打开状态
##### 验证 Feign client 指定方法生效
先访问 http://localhost/test/feignMethod/false 2次 1秒内
再访问 http://localhost/test/feignMethod/true 断路器处于打开状态
#### 规则动态刷新
修改配置中心的规则, 再访问上述接口。
### Sentinel OpenFeign Example
本 Example 演示 OpenFeing 与 Sentinel 的整合。Example 中使用 httpbin 充当后台 API 接口服务。
#### 项目编写
> **注意:本项目中代码已经完成相对应的功能,不需要再进行任何修改。**
项目支持两种启动方式:通过主类 `OpenFeignApplication` 启动和 Jar 包启动两种方式。
#### 调用测试
项目启动完成之后,可以通过访问对应的 URL 访问,查看对应的 Sentinel 流控效果。
> **注意:项目中提供的 RestTemplate 和 Webclient Example 同理。**
## Endpoint 信息查看
Spring Boot 应用支持通过 Endpoint 来暴露相关信息,`spring-cloud-starter-alibaba-sentinel` 也支持这一点。
在使用之前需要在 Maven 中添加 `spring-boot-starter-actuator`依赖,并在配置中允许 Endpoints 的访问。
* Spring Boot 1.x 中添加配置 `management.security.enabled=false`
* Spring Boot 2.x 中添加配置 `management.endpoints.web.exposure.include=*`
Spring Boot 1.x 可以通过访问 http://127.0.0.1:18083/sentinel 来查看 Sentinel Endpoint 的信息。Spring Boot 2.x 可以通过访问 http://127.0.0.1:18083/actuator/sentinel 来访问。
<p align="center"><img src="https://cdn.yuque.com/lark/0/2018/png/54319/1532084199224-1a41591d-7a06-4680-be8a-5de319ac635d.png" width="480" heigh='360' ></p>
## 查看实时监控
Sentinel 控制台支持实时监控查看,您可以通过 Sentinel 控制台查看各链路的请求的通过数和被限流数等信息。
其中 `p_qps` 为通过(pass) 流控的 QPS`b_qps` 为被限流 (block) 的 QPS。
<p align="center"><img src="https://cdn.nlark.com/lark/0/2018/png/54319/1532313595369-8428cd7d-9eb7-4786-a149-acf0da4a2daf.png" width="480" heigh='180' ></p>
## ReadableDataSource 支持
Sentinel 内部提供了[动态规则的扩展实现 ReadableDataSource](https://github.com/alibaba/Sentinel/wiki/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%99%E6%89%A9%E5%B1%95#datasource-%E6%89%A9%E5%B1%95)。
Sentinel starter 整合了目前存在的几类 ReadableDataSource。只需要在配置文件中进行相关配置即可在 Spring 容器中自动注册 DataSource。
比如要定义两个ReadableDataSource分别是 `FileRefreshableDataSource``NacosDataSource`,配置如下:
```properties
spring.cloud.sentinel.datasource.ds1.file.file=classpath: degraderule.json
spring.cloud.sentinel.datasource.ds1.file.data-type=json
spring.cloud.sentinel.datasource.ds2.nacos.server-addr=127.0.0.1:8848
spring.cloud.sentinel.datasource.ds2.nacos.dataId=sentinel
spring.cloud.sentinel.datasource.ds2.nacos.groupId=DEFAULT_GROUP
spring.cloud.sentinel.datasource.ds2.nacos.data-type=json
```
`ds1``ds2` 表示ReadableDataSource的名称可随意编写。`ds1` 和 `ds2` 后面的 `file``nacos` 表示ReadableDataSource的类型。
目前支持`file`, `nacos`, `zk`, `apollo``redis` 这5种类型。
其中`nacos``zk``apollo``redis` 这4种类型的使用需要加上对应的依赖`sentinel-datasource-nacos`, `sentinel-datasource-zookeeper`, `sentinel-datasource-apollo`, `sentinel-datasource-redis`
`ReadableDataSource` 加载规则数据成功的时候,控制台会打印出相应的日志信息:
```
[Sentinel Starter] DataSource ds1-sentinel-file-datasource load 3 DegradeRule
[Sentinel Starter] DataSource ds2-sentinel-nacos-datasource load 2 FlowRule
```
## More
Sentinel 是一款功能强大的中间件,从流量控制,熔断降级,系统负载保护等多个维度保护服务的稳定性。此 Demo 仅演示了 使用 Sentinel 作为限流工具的使用,更多 Sentinel 相关的信息,请参考 [Sentinel 项目](https://github.com/alibaba/Sentinel)。
如果您对 `spring-cloud-starter-alibaba-sentinel` 有任何建议或想法,欢迎在 issue 中或者通过其他社区渠道向我们提出。

@ -0,0 +1,316 @@
# Spring Cloud Alibaba Sentinel Example
## Project description
This Example project demonstrates how to use `spring-cloud-starter-alibaba-sentinel` to complete the traffic management function in Spring Cloud applications.
[Sentinel](https://github.com/alibaba/Sentinel) It is the traffic defense component of Alibaba's open source distributed system. Sentinel takes traffic as the entry point to protect the stability of services from multiple dimensions such as traffic control, fuse degradation, system load protection, etc.
## Sentinel Example
In this Example project, the Sentinel circuit breaker is mainly demonstrated, and the Spring Cloud Gateway is integrated with the use of OpenFeign, RestTemplate, and Webclient.
### Download and launch Sentinel Console
1. First, you need to obtain the Sentinel Console, which supports direct download and source code construction
1. Direct download: [Download the Sentinel console](https://github.com/alibaba/Sentinel/releases)
2. Source code construction: Enter Sentinel [Github project page](https://github.com/alibaba/Sentinel), clone the code to the local compilation and packaging [参考此文档](https://github.com/alibaba/Sentinel/blob/1.8/sentinel-dashboard/README.md).
2. Start the console and execute the Java command `java -jar sentinel-dashboard.jar` to finish starting the Sentinel console.
The default console listening port is `8080`. The Sentinel console is developed using the Spring Boot programming model. If you need to specify other ports, please use the standard method of Spring Boot container configuration. For details, please refer to [Spring Boot documentation](https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-customizing-embedded-containers).
### Sentinel Core Example
This Example module mainly demonstrates how to use the basic functions of Sentinel to complete the traffic control of Spring Cloud applications. Before launching Example for a demonstration, let's look at how to access the Sentinel component in a Spring Cloud application.
#### Project preparation
> **Note: This document is only for the purpose of understanding the access method. The access work is done in this sample code, and you do not need to modify it.**
1. First, modify `pom.xml` the file to introduce Sentinel starter.
```xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
```
2. Access current-limiting buried point
- `spring-cloud-starter-alibaba-sentinel` By default, all HTTP services provide the current limiting embedded point. If you only want to limit the current of the HTTP service, you only need to introduce the dependency and do not need to modify the code.
- Custom Buried Point If you need to limit or degrade a specific method, you can use `@SentinelResource` annotations to complete the current limiting buried point. The example code is as follows:
```java
@SentinelResource("resource")
public String hello() {
return "Hello";
}
```
Of course, it can also be buried by the original `SphU.entry(xxx)` method, which can be seen [Sentinel documentation](https://github.com/alibaba/Sentinel/wiki/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8#%E5%AE%9A%E4%B9%89%E8%B5%84%E6%BA%90).
3. Configure the current limit rule
Sentinel provides two ways to configure throttling rules: code configuration and console configuration. The method used in this example is configuration through code.
1. Configure rate limits by code. Here is a simple code example of rate limit configuration. For more configuration details, see [Sentinel documentation](https://github.com/alibaba/Sentinel/wiki/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8#%E5%AE%9A%E4%B9%89%E8%A7%84%E5%88%99).
```java
List<FlowRule> rules = new ArrayList<FlowRule>();
FlowRule rule = new FlowRule();
rule.setResource(str);
// set limit qps to 10
rule.setCount(10);
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setLimitApp("default");
rules.add(rule);
FlowRuleManager.loadRules(rules);
```
2. Please refer to the graphic description at the end of the article for current limiting rule configuration through the console.
#### The application starts
1. Add configuration, and add basic configuration information in the application `/src/main/resources/application.yml`
```yaml
server:
port: 18083
spring:
application:
name: sentinel-core-example
cloud:
sentinel:
transport:
dashboard: localhost:8080
```
2. Start the application, support IDE direct start and start after compilation and packaging.
1. IDE direct startup: find the main class `SentinelCoreApplication` and execute the main method to start the application.
2. Start after packaging and compiling: First execute `mvn clean package` to package the project compilation, and then execute `java -jar sentinel-core-example.jar` to start the application.
#### Invoke service validation
Use the curl command to call the two URLs separately, and you can see that the access is successful.
```shell
$ curl http://localhost:18083/test
Blocked by Sentinel (flow limiting)
$ curl http://localhost:18083/hello
Hello
```
#### Configure and verify the current limit rule
1. Visit the http://localhost:8080 page and log in. The default user name and password are: `sentinel`.
On the left, you can see that the Sentinel-Example application has been registered to the console. Click **Flow control rules** it, and you can see that the current flow control rule is empty.
> ** Note: If you do not find the application in the console, please call the URL or method with Sentinel buried points, because Sentinel uses lazy load policy. For detailed troubleshooting procedures, see [Sentinel FAQ](https://github.com/alibaba/Sentinel/wiki/FAQ). **
<p align="center"><img src="https://cdn.nlark.com/lark/0/2018/png/54319/1532315951819-9ffd959e-0547-4f61-8f06-91374cfe7f21.png" width="700" heigh='400' ></p>
2. Configure URL flow limit rule: click Add Flow Control Rule, fill in the URL relative path to be restricted for the resource name, select the threshold to be restricted for the single machine threshold, and click Add to confirm. (The value is set to 1 for demonstration purposes.).
<p align="center"><img src="https://cdn.yuque.com/lark/0/2018/png/54319/1532078717483-62ab74cd-e5da-4241-a45d-66166b1bde99.png" width="480" heigh='180' ></p>
3. Configure custom current limiting rules: click Add a flow control rule, fill in `@SentinelResource` the value of the comment `value` field for the resource name, select the threshold for current limiting for the single machine threshold, and click Add to confirm. (The value is set to 1 for demonstration purposes.).
<p align="center"><img src="https://cdn.yuque.com/lark/0/2018/png/54319/1532080384317-2943ce0a-daaf-495d-8afc-79a0248a119a.png" width="480" heigh='180' ></p>
4. Visit the URL. When the QPS exceeds 1, you can see the effect of limiting the current as follows.
<p align="center"><img src="https://cdn.yuque.com/lark/0/2018/png/54319/1532080652178-be119c4a-2a08-4f67-be70-fe5ed9a248a3.png" width="480" heigh='180' ></p>
<p align="center"><img src="https://cdn.yuque.com/lark/0/2018/png/54319/1532080661437-b84ee161-6c2d-4df2-bdb7-7cf0d5be92fb.png" width="480" heigh='180' ></p>
#### Custom current limit processing logic
* Default Current Limit Exception Handling
After the URL current limiting is triggered, the default processing logic is to directly return to "Blocked by Sentinel". If you need to customize the processing logic, the implementation method is as follows:
```java
public class CustomUrlBlockHandler implements UrlBlockHandler {
@Override
public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
// todo add your logic
}
}
WebCallbackManager.setUrlBlockHandler(new CustomUrlBlockHandler());
```
* Current limit exception handling using `@SentinelResource` annotations
If you need to customize the processing logic, fill in `@SentinelResource` the attribute of the note `blockHandler` (for all types `BlockException`, you need to make your own judgment) or `fallback` the attribute (for the fuse degradation exception). **There are restrictions on the signature and location of the corresponding method** See for [Sentinel Annotation Support Document](https://github.com/alibaba/Sentinel/wiki/%E6%B3%A8%E8%A7%A3%E6%94%AF%E6%8C%81#sentinelresource-%E6%B3%A8%E8%A7%A3) details. An example implementation is as follows:
```java
public class TestService {
// blockHandler 是位于 ExceptionUtil 类下的 handleException 静态方法,需符合对应的类型限制.
@SentinelResource(value = "test", blockHandler = "handleException", blockHandlerClass = {ExceptionUtil.class})
public void test() {
System.out.println("Test");
}
// blockHandler 是位于当前类下的 exceptionHandler 方法,需符合对应的类型限制.
@SentinelResource(value = "hello", blockHandler = "exceptionHandler")
public String hello(long s) {
return String.format("Hello at %d", s);
}
public String exceptionHandler(long s, BlockException ex) {
// Do some log here.
ex.printStackTrace();
return "Oops, error occurred at " + s;
}
}
public final class ExceptionUtil {
public static void handleException(BlockException ex) {
System.out.println("Oops: " + ex.getClass().getCanonicalName());
}
}
```
A simple `@SentinelResource` example can be found in [sentinel-demo-annotation-spring-aop](https://github.com/alibaba/Sentinel/tree/2021.x/sentinel-demo/sentinel-demo-annotation-spring-aop).
### Sentinel Circuitbreaker Example
This Example mainly demonstrates the use of OpenFeign integrated Sentinel circuit breaker.
#### Prepare the configuration file
1. Add a configuration to the Configuration Center. DataId is `sentinel-circuitbreaker-rules.yml`
```yml
feign:
circuitbreaker:
enabled: true # 开启 feign 断路器支持
sentinel:
default-rule: default # 默认规则名称
rules:
# 默认规则, 对所有 feign client 生效
default:
- grade: 2 # 根据异常数目降级
count: 1
timeWindow: 15 # 降级后到半开状态的时间
statIntervalMs: 1000
minRequestAmount: 1
# 只对 feign client user 生效
user:
- grade: 2
count: 1
timeWindow: 15
statIntervalMs: 1000
minRequestAmount: 1
# 只对 feign client user 的方法 feignMethod 生效
# 括号里是参数类型, 多个逗号分割, 比如 user#method(boolean,String,Map)
"[user#feignMethod(boolean)]":
- grade: 2
count: 1
timeWindow: 10
statIntervalMs: 1000
minRequestAmount: 1
```
#### Verify that the configuration is in effect
Start the project main class `FeignCircuitBreakerApplication`
##### Verify that the default Feign client takes effect
Access http://localhost/test/default/false 2 times (within 1 second) and then access http://localhost/test/default/true the circuit breaker in the open state
##### Verify that the specified Feign client is in effect
Access http://localhost/test/feign/false 2 times (within 1 second) and then access http://localhost/test/feign/true the circuit breaker in the open state
##### Verify that the Feign client specified method takes effect
Access http://localhost/test/feignMethod/false 2 times (within 1 second) and then access http://localhost/test/feignMethod/true the circuit breaker in the open state
#### Rule dynamic refresh
Modify the rules of the configuration center, and then access the above interface.
### Sentinel OpenFeign Example
This Example demonstrates the integration of OpenFeing and Sentinel. In Example, httpbin is used as a background API interface service.
#### Project preparation
> **Note: The code in this project has completed the corresponding function and does not need to be modified.**
The project supports two startup modes: startup through the main class `OpenFeignApplication` and startup through the Jar package.
#### Call the test
After the project is started, you can access the corresponding URL to view the corresponding Sentinel flow control effect.
> **Note: The RestTemplate provided in the project is the same as the Webclient Example.**
## Endpoint information viewing
Spring Boot applications support the exposure of relevant information through Endpoints, `spring-cloud-starter-alibaba-sentinel` as well.
Before using it, you need to add `spring-boot-starter-actuator` dependencies in Maven and allow Endpoints access in the configuration.
* Add configuration in Spring Boot 1.x
* Adding Configuration in Spring Boot 2.x
Spring Boot 1.x can view Sentinel Endpoint information by visiting http://127.0.0.1:18083/sentinel . Spring Boot 2.x can be accessed by visiting http://127.0.0.1:18083/actuator/sentinel .
<p align="center"><img src="https://cdn.yuque.com/lark/0/2018/png/54319/1532084199224-1a41591d-7a06-4680-be8a-5de319ac635d.png" width="480" heigh='360' ></p>
## View real-time monitoring
The Sentinel console supports real-time monitoring and viewing. You can view information such as the number of requests passed and the number of throttled flows for each link through the Sentinel console. Where `p_qps` is a pass flow controlled QPS and `b_qps` is a blocked QPS.
<p align="center"><img src="https://cdn.nlark.com/lark/0/2018/png/54319/1532313595369-8428cd7d-9eb7-4786-a149-acf0da4a2daf.png" width="480" heigh='180' ></p>
## ReadableData Source support
The Sentinel provides [Implementation of ReadableDataSource by Extending Dynamic Rule](https://github.com/alibaba/Sentinel/wiki/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%99%E6%89%A9%E5%B1%95#datasource-%E6%89%A9%E5%B1%95) internally.
Sentinel starter incorporates several classes of ReadableDataSources that exist today. The DataSource is automatically registered in the Spring container by simply making the relevant configuration in the configuration file.
`FileRefreshableDataSource` and `NacosDataSource`, configured as follows:
```properties
spring.cloud.sentinel.datasource.ds1.file.file=classpath: degraderule.json
spring.cloud.sentinel.datasource.ds1.file.data-type=json
spring.cloud.sentinel.datasource.ds2.nacos.server-addr=127.0.0.1:8848
spring.cloud.sentinel.datasource.ds2.nacos.dataId=sentinel
spring.cloud.sentinel.datasource.ds2.nacos.groupId=DEFAULT_GROUP
spring.cloud.sentinel.datasource.ds2.nacos.data-type=json
```
`ds1` And `ds2` the name that represents the ReadableDataSource. Feel free to write. The sum `nacos` following `file` the `ds1` and `ds2` represents the type of the ReadableDataSource.
Currently supports `file`, `nacos`, `zk` `apollo`, `redis` these 5 types.
Among them `nacos` `zk` `apollo`, the use of `redis` these four types requires the addition of corresponding dependencies `sentinel-datasource-nacos` `sentinel-datasource-zookeeper` `sentinel-datasource-apollo` `sentinel-datasource-redis`.
When `ReadableDataSource` the rule data is loaded successfully, the console will print out the corresponding log information:
```
[Sentinel Starter] DataSource ds1-sentinel-file-datasource load 3 DegradeRule
[Sentinel Starter] DataSource ds2-sentinel-nacos-datasource load 2 FlowRule
```
## More
Sentinel is a powerful middleware that protects the stability of services from multiple dimensions such as flow control, fuse degradation, and system load protection. This Demo only demonstrates the use of Sentinel as a current limiting tool. For more information about Sentinel, please refer to [Project Sentinel](https://github.com/alibaba/Sentinel).
If you `spring-cloud-starter-alibaba-sentinel` have any suggestions or ideas, please feel free to send them to us in the issue or through other community channels.

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

@ -1,65 +0,0 @@
# Sentinel Feign Circuit Breaker Example
## 项目说明
Spring Cloud OpenFeign 整合 Sentinel 断路器实现。
## 项目示例
1. 添加配置到配置中心
dataId 为 `sentinel-circuitbreaker-rules.yml`
```yaml
feign:
circuitbreaker:
enabled: true # 开启 feign 断路器支持
sentinel:
default-rule: default # 默认规则名称
rules:
# 默认规则, 对所有 feign client 生效
default:
- grade: 2 # 根据异常数目降级
count: 1
timeWindow: 15 # 降级后到半开状态的时间
statIntervalMs: 1000
minRequestAmount: 1
# 只对 feign client user 生效
user:
- grade: 2
count: 1
timeWindow: 15
statIntervalMs: 1000
minRequestAmount: 1
# 只对 feign client user 的方法 feignMethod 生效
# 括号里是参数类型, 多个逗号分割, 比如 user#method(boolean,String,Map)
"[user#feignMethod(boolean)]":
- grade: 2
count: 1
timeWindow: 10
statIntervalMs: 1000
minRequestAmount: 1
```
## 验证配置生效
启动项目主类 `FeignCircuitBreakerApplication`
### 验证默认 Feign client 生效
先访问 http://localhost/test/default/false 2 次 1秒内
再访问 http://localhost/test/default/true 断路器处于打开状态
### 验证指定 Feign client 生效
先访问 http://localhost/test/feign/false 2 次 1秒内
再访问 http://localhost/test/feign/true 断路器处于打开状态
### 验证 Feign client 指定方法生效
先访问 http://localhost/test/feignMethod/false 2次 1秒内
再访问 http://localhost/test/feignMethod/true 断路器处于打开状态
## 规则动态刷新
修改配置中心的规则, 再访问上述接口。

@ -1,63 +0,0 @@
# Sentinel Feign Circuit Breaker Example
## Project description
Spring Cloud OpenFeign integrates Sentinel circuit breaker implementation.
## sample
1. add configuration to config center.
```yaml
feign:
circuitbreaker:
enabled: true # Enable feign circuit breaker support
sentinel:
default-rule: default # Default rule name
rules:
# Default rule, valid for all feign clients
default:
- grade: 2 # Downgrade based on number of exceptions
count: 1
timeWindow: 15 # Time to half-open state after downgrade
statIntervalMs: 1000
minRequestAmount: 1
# Only valid for feign client user
user:
- grade: 2
count: 1
timeWindow: 15
statIntervalMs: 1000
minRequestAmount: 1
# Only valid for the method feignMethod of the feign client user
# Parentheses are parameter types, separated by multiple commas, such as user#method(boolean,String,Map)
"[user#feignMethod(boolean)]":
- grade: 2
count: 1
timeWindow: 10
statIntervalMs: 1000
minRequestAmount: 1
```
## Verify
Startup project main class `FeignCircuitBreakerApplication`
### Verify that the default Feign client takes effect.
First visit http:localhost/test/default/false 2 times (in 1 second)
and then visit http:localhost/test/default/true, the circuit breaker is open
### Verify that the specified Feign client takes effect.
First visit http:localhost/test/feign/false 2 times (in 1 second)
and then visit http:localhost/test/feign/true, the circuit breaker is open
### Verify that the specified method of Feign client takes effect.
First visit http://localhost/test/feignMethod/false 2 times (in 1 second)
and then visit http://localhost/test/feignMethod/true, the circuit breaker is open
## Rules are dynamically refreshed
Modify the rules of the configuration center, and then access the above interface

@ -1,9 +1,26 @@
#
# Copyright 2023-2024 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
server:
port: 80
spring:
application:
name: circuit-breaker-app
name: sentinel-circuit-breaker-example
cloud:
nacos:
config:

@ -1,3 +1,19 @@
#
# Copyright 2023-2024 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
feign:
circuitbreaker:
enabled: true

@ -1,232 +0,0 @@
# Sentinel Example
## 项目说明
本项目演示如何使用 spring-cloud-starter-alibaba-sentinel 完成 Spring Cloud 应用的限流管理。
[Sentinel](https://github.com/alibaba/Sentinel) 是阿里巴巴开源的分布式系统的流量防卫组件Sentinel 把流量作为切入点,从流量控制,熔断降级,系统负载保护等多个维度保护服务的稳定性。
## 示例
### 如何接入
在启动示例进行演示之前,我们先了解一下如何接入 Sentinel。
> **注意:本章节只是为了便于您理解接入方式,本示例代码中已经完成接入工作,您无需再进行修改。**
1. 首先,修改 `pom.xml` 文件,引入 Sentinel starter。
```xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
```
2. 接入限流埋点
- HTTP 埋点
`spring-cloud-starter-alibaba-sentinel` 默认为所有的 HTTP 服务提供了限流埋点,如果只想对 HTTP 服务进行限流,那么只需要引入依赖,无需修改代码。
- 自定义埋点
如果需要对某个特定的方法进行限流或降级,可以通过 `@SentinelResource` 注解来完成限流的埋点,示例代码如下:
```java
@SentinelResource("resource")
public String hello() {
return "Hello";
}
```
当然也可以通过原始的 `SphU.entry(xxx)` 方法进行埋点,可以参见 [Sentinel 文档](https://github.com/alibaba/Sentinel/wiki/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8#%E5%AE%9A%E4%B9%89%E8%B5%84%E6%BA%90)。
3. 配置限流规则
Sentinel 提供了两种配置限流规则的方式:代码配置 和 控制台配置。本示例使用的方式为通过控制台配置。
1. 通过代码来实现限流规则的配置。一个简单的限流规则配置示例代码如下,更多限流规则配置详情请参考 [Sentinel 文档](https://github.com/alibaba/Sentinel/wiki/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8#%E5%AE%9A%E4%B9%89%E8%A7%84%E5%88%99)。
```java
List<FlowRule> rules = new ArrayList<FlowRule>();
FlowRule rule = new FlowRule();
rule.setResource(str);
// set limit qps to 10
rule.setCount(10);
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setLimitApp("default");
rules.add(rule);
FlowRuleManager.loadRules(rules);
```
2. 通过控制台进行限流规则配置请参考文章后面的图文说明。
### 启动 Sentinel 控制台
1. 首先需要获取 Sentinel 控制台,支持直接下载和源码构建两种方式。
1. 直接下载:[下载 Sentinel 控制台](https://github.com/alibaba/Sentinel/releases)
2. 源码构建:进入 Sentinel [Github 项目页面](https://github.com/alibaba/Sentinel),将代码 clone 到本地自行编译打包,[参考此文档](https://github.com/alibaba/Sentinel/blob/1.8/sentinel-dashboard/README.md)。
``
2. 启动控制台,执行 Java 命令 `java -jar sentinel-dashboard.jar`完成 Sentinel 控制台的启动。
控制台默认的监听端口为 8080。Sentinel 控制台使用 Spring Boot 编程模型开发,如果需要指定其他端口,请使用 Spring Boot 容器配置的标准方式,详情请参考 [Spring Boot 文档](https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-customizing-embedded-containers)。
### 应用启动
1. 增加配置,在应用的 `/src/main/resources/application.properties` 中添加基本配置信息
```properties
spring.application.name=sentinel-example
server.port=18083
spring.cloud.sentinel.transport.dashboard=localhost:8080
```
2. 启动应用,支持 IDE 直接启动和编译打包后启动。
1. IDE直接启动找到主类 `ServiceApplication`,执行 main 方法启动应用。
2. 打包编译后启动:首先执行 `mvn clean package` 将工程编译打包,然后执行 `java -jar sentinel-core-example.jar` 启动应用。
### 调用服务
使用 curl 命令分别调用两个 URL可以看到访问成功。
```shell
$ curl http://localhost:18083/test
Blocked by Sentinel (flow limiting)
$ curl http://localhost:18083/hello
Hello
```
### 配置限流规则并验证
1. 访问 http://localhost:8080 页面,进行登陆,默认用户名和密码均为:`sentinel`。
可以在左侧看到 Sentinel-Example 应用已经注册到了控制台,单击 **流控规则** ,可以看到目前的流控规则为空。
> **注意:如果您在控制台没有找到应用,请调用一下进行了 Sentinel 埋点的 URL 或方法,因为 Sentinel 使用了 lazy load 策略。详细的排查过程请参见 [Sentinel FAQ](https://github.com/alibaba/Sentinel/wiki/FAQ)。**
<p align="center"><img src="https://cdn.nlark.com/lark/0/2018/png/54319/1532315951819-9ffd959e-0547-4f61-8f06-91374cfe7f21.png" width="1000" heigh='400' ></p>
2. 配置 URL 限流规则:点击新增流控规则,资源名填写需要限流的 URL 相对路径,单机阈值选择需要限流的阈值,点击新增进行确认。(为了便于演示效果,这里将值设置成了 1)。
<p align="center"><img src="https://cdn.yuque.com/lark/0/2018/png/54319/1532078717483-62ab74cd-e5da-4241-a45d-66166b1bde99.png" width="480" heigh='180' ></p>
3. 配置自定义限流规则:点击新增流控规则,资源名填写 `@SentinelResource` 注解 `value` 字段的值,单机阈值选择需要限流的阈值,点击新增进行确认。(为了便于演示效果,这里将值设置成了 1)。
<p align="center"><img src="https://cdn.yuque.com/lark/0/2018/png/54319/1532080384317-2943ce0a-daaf-495d-8afc-79a0248a119a.png" width="480" heigh='180' ></p>
4. 访问 URL当 QPS 超过 1 时,可以看到限流效果如下。
<p align="center"><img src="https://cdn.yuque.com/lark/0/2018/png/54319/1532080652178-be119c4a-2a08-4f67-be70-fe5ed9a248a3.png" width="480" heigh='180' ></p>
<p align="center"><img src="https://cdn.yuque.com/lark/0/2018/png/54319/1532080661437-b84ee161-6c2d-4df2-bdb7-7cf0d5be92fb.png" width="480" heigh='180' ></p>
## 自定义限流处理逻辑
* 默认限流异常处理
URL 限流触发后默认处理逻辑是,直接返回 "Blocked by Sentinel (flow limiting)"。 如果需要自定义处理逻辑,实现的方式如下:
```java
public class CustomUrlBlockHandler implements UrlBlockHandler {
@Override
public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
// todo add your logic
}
}
WebCallbackManager.setUrlBlockHandler(new CustomUrlBlockHandler());
```
* 使用 `@SentinelResource` 注解下的限流异常处理
如果需要自定义处理逻辑,填写 `@SentinelResource` 注解的 `blockHandler` 属性(针对所有类型的 `BlockException`,需自行判断)或 `fallback` 属性(针对熔断降级异常),注意**对应方法的签名和位置有限制**,详情见 [Sentinel 注解支持文档](https://github.com/alibaba/Sentinel/wiki/%E6%B3%A8%E8%A7%A3%E6%94%AF%E6%8C%81#sentinelresource-%E6%B3%A8%E8%A7%A3)。示例实现如下:
```java
public class TestService {
// blockHandler 是位于 ExceptionUtil 类下的 handleException 静态方法,需符合对应的类型限制.
@SentinelResource(value = "test", blockHandler = "handleException", blockHandlerClass = {ExceptionUtil.class})
public void test() {
System.out.println("Test");
}
// blockHandler 是位于当前类下的 exceptionHandler 方法,需符合对应的类型限制.
@SentinelResource(value = "hello", blockHandler = "exceptionHandler")
public String hello(long s) {
return String.format("Hello at %d", s);
}
public String exceptionHandler(long s, BlockException ex) {
// Do some log here.
ex.printStackTrace();
return "Oops, error occurred at " + s;
}
}
```
```java
public final class ExceptionUtil {
public static void handleException(BlockException ex) {
System.out.println("Oops: " + ex.getClass().getCanonicalName());
}
}
```
一个简单的 `@SentinelResource` 示例可以见 [sentinel-demo-annotation-spring-aop](https://github.com/alibaba/Sentinel/tree/2021.x/sentinel-demo/sentinel-demo-annotation-spring-aop)。
## Endpoint 信息查看
Spring Boot 应用支持通过 Endpoint 来暴露相关信息,`spring-cloud-starter-alibaba-sentinel` 也支持这一点。
在使用之前需要在 Maven 中添加 `spring-boot-starter-actuator`依赖,并在配置中允许 Endpoints 的访问。
* Spring Boot 1.x 中添加配置 `management.security.enabled=false`
* Spring Boot 2.x 中添加配置 `management.endpoints.web.exposure.include=*`
Spring Boot 1.x 可以通过访问 http://127.0.0.1:18083/sentinel 来查看 Sentinel Endpoint 的信息。Spring Boot 2.x 可以通过访问 http://127.0.0.1:18083/actuator/sentinel 来访问。
<p align="center"><img src="https://cdn.yuque.com/lark/0/2018/png/54319/1532084199224-1a41591d-7a06-4680-be8a-5de319ac635d.png" width="480" heigh='360' ></p>
## 查看实时监控
Sentinel 控制台支持实时监控查看,您可以通过 Sentinel 控制台查看各链路的请求的通过数和被限流数等信息。
其中 `p_qps` 为通过(pass) 流控的 QPS`b_qps` 为被限流 (block) 的 QPS。
<p align="center"><img src="https://cdn.nlark.com/lark/0/2018/png/54319/1532313595369-8428cd7d-9eb7-4786-a149-acf0da4a2daf.png" width="480" heigh='180' ></p>
## ReadableDataSource 支持
Sentinel 内部提供了[动态规则的扩展实现 ReadableDataSource](https://github.com/alibaba/Sentinel/wiki/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%99%E6%89%A9%E5%B1%95#datasource-%E6%89%A9%E5%B1%95)。
Sentinel starter 整合了目前存在的几类 ReadableDataSource。只需要在配置文件中进行相关配置即可在 Spring 容器中自动注册 DataSource。
比如要定义两个ReadableDataSource分别是 `FileRefreshableDataSource``NacosDataSource`,配置如下:
```properties
spring.cloud.sentinel.datasource.ds1.file.file=classpath: degraderule.json
spring.cloud.sentinel.datasource.ds1.file.data-type=json
spring.cloud.sentinel.datasource.ds2.nacos.server-addr=127.0.0.1:8848
spring.cloud.sentinel.datasource.ds2.nacos.dataId=sentinel
spring.cloud.sentinel.datasource.ds2.nacos.groupId=DEFAULT_GROUP
spring.cloud.sentinel.datasource.ds2.nacos.data-type=json
```
`ds1``ds2` 表示ReadableDataSource的名称可随意编写。`ds1` 和 `ds2` 后面的 `file``nacos` 表示ReadableDataSource的类型。
目前支持`file`, `nacos`, `zk`, `apollo``redis` 这5种类型。
其中`nacos``zk``apollo``redis` 这4种类型的使用需要加上对应的依赖`sentinel-datasource-nacos`, `sentinel-datasource-zookeeper`, `sentinel-datasource-apollo`, `sentinel-datasource-redis`
`ReadableDataSource` 加载规则数据成功的时候,控制台会打印出相应的日志信息:
```
[Sentinel Starter] DataSource ds1-sentinel-file-datasource load 3 DegradeRule
[Sentinel Starter] DataSource ds2-sentinel-nacos-datasource load 2 FlowRule
```
## More
Sentinel 是一款功能强大的中间件,从流量控制,熔断降级,系统负载保护等多个维度保护服务的稳定性。此 Demo 仅演示了 使用 Sentinel 作为限流工具的使用,更多 Sentinel 相关的信息,请参考 [Sentinel 项目](https://github.com/alibaba/Sentinel)。
如果您对 `spring-cloud-starter-alibaba-sentinel` 有任何建议或想法,欢迎在 issue 中或者通过其他社区渠道向我们提出。

@ -1,240 +0,0 @@
# Sentinel Example
## Project Instruction
This example illustrates how to use Sentinel starter to implement flow control for Spring Cloud applications.
[Sentinel](https://github.com/alibaba/Sentinel) is an open-source project of Alibaba. Sentinel takes "traffic flow" as the breakthrough point, and provides solutions in areas such as flow control, concurrency, circuit breaking, and load protection to protect service stability.
## Demo
### Connect to Sentinel
Before we start the demo, let's learn how to connect Sentinel to a Spring Cloud application.
**Note: This section is to show you how to connect to Sentinel. The configurations have been completed in the following example, so you don't need modify the code any more.**
1. Add dependency spring-cloud-starter-alibaba-sentinel in the pom.xml file in your Spring Cloud project.
```xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
```
2. Define Resources
1. Define HTTP Resources
`spring-cloud-starter-alibaba-sentinel` defines all HTTP URLS as resources by relative paths. If you only want to add flow control for your HTTP services, you do not need to modify your code.
2. Define Custom Resources
If you want to implement flow control or degradation for a specific method, you can add an @SentinelResource annotation to the method, as shown in the code below.
```java
@SentinelResource("resource")
public String hello() {
return "Hello";
}
```
3. Configure flow control rules
Sentinel provides two ways to configure flow control rules, init from code or configure by dashboard.
1. Init rule from code: See the code below for a simple flow rule. See [Sentinel Docs](https://github.com/alibaba/Sentinel/wiki/How-to-Use#define-rules) for more information about flow rules.
```java
List<FlowRule> rules = new ArrayList<FlowRule>();
FlowRule rule = new FlowRule();
rule.setResource(str);
// set limit qps to 10
rule.setCount(10);
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setLimitApp("default");
rules.add(rule);
FlowRuleManager.loadRules(rules);
```
2. Config by dashboard: See the following section.
### Start Sentinel Dashboard
1. Install Sentinel dashboard by downloading a fatjar or build from source code.
1. Download: [Download Sentinel Dashboard](https://github.com/alibaba/Sentinel/releases)
2. Build from source code: Get source code by `git clone git@github.com:alibaba/Sentinel.git` from [Github Sentinel](https://github.com/alibaba/Sentinel) and build your code. See [build reference](https://github.com/alibaba/Sentinel/blob/1.8/sentinel-dashboard/README.md) for details.
2. Start the dashboard by running the `java -jar sentinel-dashboard.jar` command.
The default port of Sentinel dashboard is 8080. Sentinel dashboard is a Spring Boot project. If you want to use another port, see [Spring Boot Reference](https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-customizing-embedded-containers).
### Start Application
1. Add necessary configurations to file `/src/main/resources/application.properties`.
```properties
spring.application.name=sentinel-example
server.port=18083
spring.cloud.sentinel.transport.dashboard=localhost:8080
```
2. Start the application in IDE or by building a fatjar.
1. Start in IDE: Find main class `ServiceApplication`, and execute the main method.
2. Build a fatjarExecute command `mvn clean package` to build a fatjar, and run command `java -jar sentinel-core-example.jar` to start the application.
### Invoke Service
Use curl command to call two URLs, you can see:
```shell
$ curl http://localhost:18083/test
Blocked by Sentinel (flow limiting)
$ curl http://localhost:18083/hello
Hello
```
### Configure Flow Control
1. Open http://localhost:8080 in browser. The defaule username and password is `sentienl`. and you can find a Sentinel-Example Application has been registered to the dashboard.
**Note: If you can't find your application in the dashboard, invoke a method that has been defined as a Sentinel Resource, for Sentinel uses lazy load strategy.**
<p align="center"><img src="https://cdn.nlark.com/lark/0/2018/png/54319/1532315951819-9ffd959e-0547-4f61-8f06-91374cfe7f21.png" width="1000" heigh='400' ></p>
2. Configure HTTP Resource Flow RuleClick **流控规则(Flow Rule)** on the left-side navigation pane and **新增流控规则(Create Flow Rule)**. On the Create Flow Rule dialogbox, type the URL relative path in the **资源名(Resource Name)** field , enter **单机阈值(Threshold)** value, then click **新增(OK)**. Here we set threshold to 1 for demonstration purpose.
<p align="center"><img src="https://cdn.yuque.com/lark/0/2018/png/54319/1532078717483-62ab74cd-e5da-4241-a45d-66166b1bde99.png" width="480" heigh='180' ></p>
3. Configure Custom Resource Flow RuleClick **流控规则(Flow Rule)** on the left-side navigation pane and **新增流控规则(Create Flow Rule)**. type the value() of @SentinelResource in the **资源名(Resource Name)** field , enter **单机阈值(Threshold)** value, then click **新增(OK)**.Here we set threshold to 1 for demonstration purpose.
<p align="center"><img src="https://cdn.yuque.com/lark/0/2018/png/54319/1532080384317-2943ce0a-daaf-495d-8afc-79a0248a119a.png" width="480" heigh='180' ></p>
4. Visit the URL in your browser again. When QPS is more than 1, we can see that flow control takes effect.
<p align="center"><img src="https://cdn.yuque.com/lark/0/2018/png/54319/1532080652178-be119c4a-2a08-4f67-be70-fe5ed9a248a3.png" width="480" heigh='180' ></p>
<p align="center"><img src="https://cdn.yuque.com/lark/0/2018/png/54319/1532080661437-b84ee161-6c2d-4df2-bdb7-7cf0d5be92fb.png" width="480" heigh='180' ></p>
## Customize Flow Control Logic
* Flow control exception handle by default
When a URL resource is blocked by Sentinel, the default logic is return HTTP response "Blocked by Sentinel (flow limiting)".
```java
public class CustomUrlBlockHandler implements UrlBlockHandler {
@Override
public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
// todo add your logic
}
}
WebCallbackManager.setUrlBlockHandler(new CustomUrlBlockHandler());
```
* Flow control exception handle by using `@SentinelResource`
When a custom resource is blocked by Sentinel, the default logic is throw BlockException.
```java
public class TestService {
@SentinelResource(value = "test", blockHandler = "handleException", blockHandlerClass = {ExceptionUtil.class})
public void test() {
System.out.println("Test");
}
@SentinelResource(value = "hello", blockHandler = "exceptionHandler")
public String hello(long s) {
return String.format("Hello at %d", s);
}
public String exceptionHandler(long s, BlockException ex) {
// Do some log here.
ex.printStackTrace();
return "Oops, error occurred at " + s;
}
}
```
```java
public final class ExceptionUtil {
public static void handleException(BlockException ex) {
System.out.println("Oops: " + ex.getClass().getCanonicalName());
}
}
```
## Endpoint
Sentinel starter also supports the implementation of Spring Boot actuator endpoints.
**Prerequisite:**
Add dependency `spring-boot-starter-actuator` to your pom.xml file, and configure your endpoint security strategy.
* Spring Boot1.x: Add configuration `management.security.enabled=false`
* Spring Boot2.x: Add configuration `management.endpoints.web.exposure.include=*`
To view the endpoint information, visit the following URLS:
* Spring Boot1.x: Sentinel Endpoint URL is http://127.0.0.1:18083/sentinel.
* Spring Boot2.x: Sentinel Endpoint URL is http://127.0.0.1:18083/actuator/sentinel.
<p align="center"><img src="https://cdn.yuque.com/lark/0/2018/png/54319/1532084199224-1a41591d-7a06-4680-be8a-5de319ac635d.png" width="480" heigh='360'></p>
## Metrics
You can view metrics information on Sentinel Dashboard.
To see the metrics, click **Real time monitoring(Real-time Monitoring)** in the left-side navigation pane.
`p_qps` stands for passed requests per second, `b_qps` stands for blocked requests per second.
<p align="center"><img src="https://cdn.nlark.com/lark/0/2018/png/54319/1532313595369-8428cd7d-9eb7-4786-a149-acf0da4a2daf.png" width="480" heigh='180'></p>
## ReadableDataSource
Sentinel provide [ReadableDataSource](https://github.com/alibaba/Sentinel/blob/2021.x/sentinel-extension/sentinel-datasource-extension/src/main/java/com/alibaba/csp/sentinel/datasource/ReadableDataSource.java) to manage dynamic rules.
Sentinel starter integrated 4 DataSources provided by Sentinel. It will be register into Spring Context if you write some configs in `application.properties`.
If you want to define `FileRefreshableDataSource` and `NacosDataSource`, see the code below:
```properties
spring.cloud.sentinel.datasource.ds1.file.file=classpath: degraderule.json
spring.cloud.sentinel.datasource.ds1.file.data-type=json
spring.cloud.sentinel.datasource.ds2.nacos.server-addr=127.0.0.1:8848
spring.cloud.sentinel.datasource.ds2.nacos.dataId=sentinel
spring.cloud.sentinel.datasource.ds2.nacos.groupId=DEFAULT_GROUP
spring.cloud.sentinel.datasource.ds2.nacos.data-type=json
```
`ds1` and `ds2` means the name of ReadableDataSource, you can write whatever you want. The `file` and `nacos` after name `ds1` and `ds2` means the type of ReadableDataSource.
Now ReadableDataSource type support 5 categories: `file`, `nacos`, `zk`, `apollo` and `redis`.
If you want to use `nacos`, `zk`, `apollo` or `redis` ReadableDataSource, you could add `sentinel-datasource-nacos`, `sentinel-datasource-zookeeper`,`sentinel-datasource-apollo` or `sentinel-datasource-redis` dependency.
When ReadableDataSource load rule data successfully, console will print some logs:
```
[Sentinel Starter] DataSource ds1-sentinel-file-datasource load 3 DegradeRule
[Sentinel Starter] DataSource ds2-sentinel-nacos-datasource load 2 FlowRule
```
## Warning
You should use `file` ReadableDataSource in a fatjar carefully or you may get error like this below
```
java.lang.RuntimeException: [Sentinel Starter] DataSource ds1 handle file [classpath: flowrule.json] error: class path resource [flowrule.json] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:xxx/xxx.jar!/BOOT-INF/classes!/flowrule.jso
```
You could use absolute path when you use File datasource & fat jar.
It is recommended to use Nacos/Apollo/Zookeeper/Redis datasource to store rules.
https://github.com/alibaba/spring-cloud-alibaba/issues/428
## More
For more information about Sentinel, see [Sentinel Project](https://github.com/alibaba/Sentinel).
If you have any ideas or suggestions for Spring Cloud Sentinel starter, please don't hesitate to tell us by submitting github issues.

@ -35,7 +35,7 @@ import org.springframework.web.client.RestTemplate;
* @author xiaojing
*/
@SpringBootApplication
public class ServiceApplication {
public class SentinelCoreApplication {
@Bean
@SentinelRestTemplate(blockHandler = "handleException",
@ -67,7 +67,7 @@ public class ServiceApplication {
}
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class, args);
SpringApplication.run(SentinelCoreApplication.class, args);
}
}

@ -1,40 +0,0 @@
spring.application.name=sentinel-example
server.port=18083
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
# we can disable health check, default is enable
management.health.diskspace.enabled=false
# management.health.sentinel.enabled=false
spring.cloud.sentinel.transport.dashboard=localhost:8080
spring.cloud.sentinel.eager=true
spring.cloud.sentinel.web-context-unify=true
#spring.cloud.sentinel.block-page=/errorPage
#spring.cloud.sentinel.filter.enabled=false
#spring.cloud.sentinel.http-method-specify=false
#spring.cloud.sentinel.datasource.ds6.nacos.server-addr=127.0.0.1:8848
#spring.cloud.sentinel.datasource.ds6.nacos.username=nacos
#spring.cloud.sentinel.datasource.ds6.nacos.password=nacos
#spring.cloud.sentinel.datasource.ds6.nacos.dataId=flowrule.json
#spring.cloud.sentinel.datasource.ds6.nacos.data-type=json
#spring.cloud.sentinel.datasource.ds6.nacos.rule-type=flow
spring.cloud.sentinel.datasource.ds1.file.file=classpath: flowrule.json
spring.cloud.sentinel.datasource.ds1.file.data-type=json
spring.cloud.sentinel.datasource.ds1.file.rule-type=flow
spring.cloud.sentinel.datasource.ds2.file.file=classpath: degraderule.json
spring.cloud.sentinel.datasource.ds2.file.data-type=json
spring.cloud.sentinel.datasource.ds2.file.rule-type=degrade
spring.cloud.sentinel.datasource.ds3.file.file=classpath: authority.json
spring.cloud.sentinel.datasource.ds3.file.rule-type=authority
spring.cloud.sentinel.datasource.ds4.file.file=classpath: system.json
spring.cloud.sentinel.datasource.ds4.file.rule-type=system
spring.cloud.sentinel.datasource.ds5.file.file=classpath: param-flow.json
spring.cloud.sentinel.datasource.ds5.file.rule-type=param_flow

@ -0,0 +1,80 @@
#
# Copyright 2023-2024 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
spring:
application:
name: sentinel-core-example
cloud:
sentinel:
transport:
dashboard: localhost:8080
datasource:
ds1:
file:
file: classpath:flowrule.json
data-type: json
rule-type: flow
ds2:
file:
file: classpath:degraderule.json
data-type: json
rule-type: degrade
ds3:
file:
file: classpath:authority.json
data-type: json
rule-type: authority
ds4:
file:
file: classpath:system.json
data-type: json
rule-type: system
ds5:
file:
file: classpath:param-flow.json
data-type: json
rule-type: param_flow
ds6:
nacos:
server-addr: 127.0.0.1:8848
username: nacos
password: nacos
data-id: flowrule.json
data-type: json
rule-type: flow
block-page: /errorPage
# filter:
# enabled: false
# http-method-specify: false
eager: true
server:
port: 18083
management:
endpoint:
web:
exposure:
include: "*"
health:
show-details: always
diskSpace:
# we can disable health check, default is enable
enabled: false
# sentinel:
# enabled: false

@ -30,6 +30,10 @@
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>

@ -18,19 +18,19 @@ package com.alibaba.cloud.examples;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* @author raozihao
* @author <a href="mailto:zihaorao@gmail.com">Steve</a>
*/
@EnableFeignClients
@SpringBootApplication
@EnableDiscoveryClient
public class OpenFeignApplication {
public static void main(String[] args) {
SpringApplication.run(OpenFeignApplication.class, args);
}

@ -29,16 +29,15 @@ import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;
/**
* @description
* @author ChengPu raozihao
* @date 2023/2/11
* @author raozihao
* @author <a href="mailto:zihaorao@gmail.com">Steve</a>
*/
@Component
public class SentinelRulesConfiguration {
/**
* You can configure sentinel rules by referring https://github.com/alibaba/Sentinel/wiki/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8#%E6%9F%A5%E8%AF%A2%E6%9B%B4%E6%94%B9%E8%A7%84%E5%88%99.
* You can configure sentinel rules by referring.
* https://sca.aliyun.com/docs/2023/user-guide/sentinel/advanced-guide/#%E6%9B%B4%E5%A4%9A%E9%85%8D%E7%BD%AE%E9%A1%B9
*/
@PostConstruct
public void init() {

@ -1,13 +1,31 @@
#
# Copyright 2023-2024 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
server:
port: 18087
spring:
application:
name: openfeign-example
name: sentinel-openfeign-example
cloud:
sentinel:
transport:
dashboard: 127.0.0.1:8081
dashboard: localhost:8080
eager: true
# Don't support run in jar by using configuration file method now, refer to https://github.com/alibaba/spring-cloud-alibaba/issues/3033
# datasource:
# ds1.file:

@ -36,7 +36,8 @@ import org.springframework.stereotype.Component;
@Component
public class SentinelRulesConfiguration {
/**
* You can configure sentinel rules by referring https://github.com/alibaba/Sentinel/wiki/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8#%E6%9F%A5%E8%AF%A2%E6%9B%B4%E6%94%B9%E8%A7%84%E5%88%99.
* You can configure sentinel rules by referring.
* https://sca.aliyun.com/docs/2023/user-guide/sentinel/advanced-guide/#%E6%9B%B4%E5%A4%9A%E9%85%8D%E7%BD%AE%E9%A1%B9
*/
@PostConstruct
public void init() {

@ -1,9 +1,32 @@
#
# Copyright 2023-2024 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
server:
port: 18088
spring:
application:
name: sentinel-resttemplate-example
cloud:
sentinel:
transport:
dashboard: localhost:8080
eager: true
# Don't support run in jar by using configuration file method now, refer to https://github.com/alibaba/spring-cloud-alibaba/issues/3033
# cloud:
# sentinel:
@ -16,4 +39,3 @@ spring:
# file: "classpath: flowrule.json"
# ruleType: "flow"
# dataType: "json"

@ -26,6 +26,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
public class SentinelSpringCloudGatewayApplication {
public static void main(String[] args) {
// GatewayCallbackManager.setRequestOriginParser(s -> "123");
SpringApplication.run(SentinelSpringCloudGatewayApplication.class, args);
}

@ -1,8 +1,26 @@
#
# Copyright 2023-2024 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
server:
port: 18085
spring:
application:
name: sentinel-spring-cloud-gateway
cloud:
gateway:
enabled: true
@ -31,6 +49,7 @@ spring:
ruleType: gw-api-group
transport:
dashboard: localhost:8080
eager: true
filter:
enabled: true
scg.fallback:
@ -40,4 +59,8 @@ spring:
scg:
order: -100
management.endpoints.web.exposure.include: "*"
management:
endpoints:
web:
exposure:
include: "*"

@ -1,8 +0,0 @@
spring.application.name=sentinel-webflux-example
server.port=18084
management.endpoints.web.exposure.include=*
spring.cloud.sentinel.transport.dashboard=localhost:8080
spring.cloud.sentinel.eager=true
spring.cloud.sentinel.datasource.ds1.file.file=classpath: flowrule.json
spring.cloud.sentinel.datasource.ds1.file.data-type=json
spring.cloud.sentinel.datasource.ds1.file.rule-type=flow

@ -0,0 +1,40 @@
#
# Copyright 2023-2024 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
server:
port: 18084
spring:
application:
name: sentinel-webflux-example
cloud:
sentinel:
transport:
dashboard: localhost:8080
eager: true
datasource:
ds1:
file:
file: classpath:flowrule.json
data-type: json
rule-type: flow
management:
endpoints:
web:
exposure:
include=*:
Loading…
Cancel
Save