feat: update sentinel example

pull/3635/head
yuluo 11 months ago
parent 5f457111a2
commit 1520ca2ff8

@ -1,127 +0,0 @@
# Sentinel Feign Example
## 项目说明
本项目演示如何使用 Sentinel starter 完成 Spring Cloud 应用调用。
[Sentinel](https://github.com/alibaba/Sentinel) 是阿里巴巴开源的分布式系统的流量防卫组件Sentinel 把流量作为切入点,从流量控制,熔断降级,系统负载保护等多个维度保护服务的稳定性。
[OpenFeign](https://github.com/spring-cloud/spring-cloud-openfeign)是一款声明式、模板化的HTTP客户端 Feign可以帮助我们更快捷、优雅地调用HTTP API。
本项目专注于Sentinel与Feign的整合关于Sentinel的更多特性可以查看[sentinel-core-example](https://github.com/alibaba/spring-cloud-alibaba/tree/2021.x/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example)。
## 示例
### 服务消费方
在启动示例进行演示之前,我们先了解一下 Feign 如何接入 Sentinel。
**注意 本章节只是为了便于您理解接入方式,本示例代码中已经完成接入工作,您无需再进行修改。**
1. 首先,修改 pom.xml 文件,引入 Sentinel starter 和 Openfeign starter。
```xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
```
2. 其次, 使用nacos 注册中心
```xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
```
3. 定义FeignClient,及其降级配置
- 定义FeignClient
```java
@FeignClient(name = "service-provider", fallbackFactory = EchoServiceFallbackFactory.class)
public interface EchoService {
/**
* 调用服务提供方的输出接口
*
* @param str 用户输入
* @return
*/
@GetMapping(value = "/echo/{str}")
String echo(@PathVariable("str") String str);
}
```
- 定义fallback 工厂,获取异常
```java
@Component
public class EchoServiceFallbackFactory implements FallbackFactory<EchoServiceFallback> {
@Override
public EchoServiceFallback create(Throwable throwable) {
return new EchoServiceFallback(throwable);
}
}
```
- 定义具体的fallback 实现
```java
public class EchoServiceFallback implements EchoService {
private Throwable throwable;
EchoServiceFallback(Throwable throwable) {
this.throwable = throwable;
}
@Override
public String echo(String str) {
return "consumer-fallback-default-str" + throwable.getMessage();
}
}
```
### 服务提供方
1. 首先, 依赖nacos 注册中心
```xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
```
2. 定义服务提供方接口
```java
@RestController
public class EchoController {
@GetMapping("/echo/{str}")
public String echo(@PathVariable String str) {
return "provider-" + str;
}
}
```
### 应用启动
支持 IDE 直接启动和编译打包后启动。
- 启动nacos 注册中心
- 启动sentinel
- 启动服务提供方:
1. IDE直接启动找到主类 `ProviderApplication`,执行 main 方法启动应用。
2. 打包编译后启动:首先执行 `mvn clean package` 将工程编译打包,然后执行 `java -jar sentinel-feign-provider-example.jar`启动应用。
- 启动服务消费方:
1. IDE直接启动找到主类 `ConsumerApplication`,执行 main 方法启动应用。
2. 打包编译后启动:首先执行 `mvn clean package` 将工程编译打包,然后执行 `java -jar sentinel-feign-consumer-example.jar`启动应用。
- 启动之后Sentinel Dashboard可能看不见service-consumer服务的详细信息多请求几次接口即可。

@ -1,126 +0,0 @@
# Sentinel Feign Example
Project description
This project demonstrates how to use Sentinel starter to complete the Spring Cloud application call.
[Sentinel](https://github.com/alibaba/Sentinel) is alibaba open source distributed system flow defense components, Sentinel flow as the breakthrough point, from the flow control, fusing the drop, the stability of the system load multiple dimensions, such as protection services.
[OpenFeign](https://github.com/spring-cloud/spring-cloud-openfeign) is a declarative, templated HTTP client, Feign can help us faster and gracefully HTTP API calls.
By focusing on this project, the integration of Sentinel and Feign more characteristics about Sentinel can view [Sentinel - core - example](https://github.com/alibaba/spring-cloud-alibaba/tree/2021.x/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example).
## sample
Service consumer
Before launching the example, let's see how Feign can access Sentinel.
** note that this section is for your convenience only. The access has been completed in this sample code and you do not need to modify it. * *
First, modify the pom.xml file to introduce Sentinel starter and Openfeign starter.
```xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
```
2. Secondly, nacos registries are used
```xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
```
3. Define the FeignClient and its degraded configuration
```java
@FeignClient(name = "service-provider", fallbackFactory = EchoServiceFallbackFactory.class)
public interface EchoService {
/**
* 调用服务提供方的输出接口
*
* @param str 用户输入
* @return
*/
@GetMapping(value = "/echo/{str}")
String echo(@PathVariable("str") String str);
}
```
- define a fallback factory to get an exception
```java
@Component
public class EchoServiceFallbackFactory implements FallbackFactory<EchoServiceFallback> {
@Override
public EchoServiceFallback create(Throwable throwable) {
return new EchoServiceFallback(throwable);
}
}
```
- define a specific fallback implementation
```java
public class EchoServiceFallback implements EchoService {
private Throwable throwable;
EchoServiceFallback(Throwable throwable) {
this.throwable = throwable;
}
@Override
public String echo(String str) {
return "consumer-fallback-default-str" + throwable.getMessage();
}
}
```
Service provider
1. First, rely on the nacos registry
```xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
```
2. Define the service provider interface
```java
@RestController
public class EchoController {
@GetMapping("/echo/{str}")
public String echo(@PathVariable String str) {
return "provider-" + str;
}
}
```
Application launch
Support for IDE startup directly and after compilation and packaging.
- launch the nacos registry
- starting service provider:
1. IDE starts directly: find the main class `ProviderApplication` and execute the main method to start the application.
2. Start after packaging and compilation: first execute `mvn clean package` to compile and package the project, and then execute `java-jar sentinel-feign-provider-example.jar` to start the application.
- starting service consumer:
1. IDE launch directly: find the main class `ConsumerApplication` and execute the main method to launch the application.
2. Start after packaging and compilation: first execute `mvn clean package` to compile and package the project, and then execute `java-jar sentinel-feign-consumer-example.jar` to start the application.

@ -2,13 +2,14 @@
## 项目说明
OpenFeign 整合 Sentinel 断路器实现
Spring Cloud OpenFeign 整合 Sentinel 断路器实现
## 示例
## 项目示例
1. 添加配置到配置中心
dataId 为 `sentinel-circuitbreaker-rules.yml`
```yaml
feign:
circuitbreaker:
@ -40,24 +41,25 @@ feign:
minRequestAmount: 1
```
2. 启动 FeignCircuitBreakerApplication
## 验证配置生效
启动项目
验证默认 feign client 生效
启动项目主类 `FeignCircuitBreakerApplication`
### 验证默认 Feign client 生效
先访问 http://localhost/test/default/false 2 次 1秒内
再访问 http://localhost/test/default/true 断路器处于打开状态
验证指定 feign client 生效
### 验证指定 Feign client 生效
先访问 http://localhost/test/feign/false 2 次 1秒内
再访问 http://localhost/test/feign/true 断路器处于打开状态
验证 feign client 指定方法生效
### 验证 Feign client 指定方法生效
先访问 http://localhost/test/feignMethod/false 2次 1秒内
再访问 http://localhost/test/feignMethod/true 断路器处于打开状态
## 规则动态刷新
修改配置中心的规则, 再访问上述接口
修改配置中心的规则, 再访问上述接口。

@ -2,11 +2,11 @@
## Project description
OpenFeign integrates Sentinel circuit breaker implementation
Spring Cloud OpenFeign integrates Sentinel circuit breaker implementation.
## sample
1. add configuration to config center
1. add configuration to config center.
```yaml
feign:
@ -38,23 +38,26 @@ feign:
statIntervalMs: 1000
minRequestAmount: 1
```
2. start FeignCircuitBreakerApplication
## Verify
Startup project
Verify that the default feign client takes effect.
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.
### 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.
### 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
Modify the rules of the configuration center, and then access the above interface

@ -1,5 +1,6 @@
server:
port: 80
spring:
application:
name: circuit-breaker-app
@ -7,5 +8,8 @@ spring:
nacos:
config:
server-addr: 127.0.0.1:8848
username: 'nacos'
password: 'nacos'
config:
import: optional:nacos:sentinel-circuitbreaker-rules.yml

@ -2,11 +2,10 @@
## 项目说明
本项目演示如何使用 Sentinel starter 完成 Spring Cloud 应用的限流管理。
本项目演示如何使用 spring-cloud-starter-alibaba-sentinel 完成 Spring Cloud 应用的限流管理。
[Sentinel](https://github.com/alibaba/Sentinel) 是阿里巴巴开源的分布式系统的流量防卫组件Sentinel 把流量作为切入点,从流量控制,熔断降级,系统负载保护等多个维度保护服务的稳定性。
## 示例
### 如何接入
@ -25,11 +24,11 @@
```
2. 接入限流埋点
- HTTP 埋点
Sentinel starter 默认为所有的 HTTP 服务提供了限流埋点,如果只想对 HTTP 服务进行限流,那么只需要引入依赖,无需修改代码。
- HTTP 埋点
`spring-cloud-starter-alibaba-sentinel` 默认为所有的 HTTP 服务提供了限流埋点,如果只想对 HTTP 服务进行限流,那么只需要引入依赖,无需修改代码。
- 自定义埋点
如果需要对某个特定的方法进行限流或降级,可以通过 `@SentinelResource` 注解来完成限流的埋点,示例代码如下:
```java
@ -65,17 +64,18 @@
1. 首先需要获取 Sentinel 控制台,支持直接下载和源码构建两种方式。
1. 直接下载:[下载 Sentinel 控制台](https://edas-public.oss-cn-hangzhou.aliyuncs.com/install_package/demo/sentinel-dashboard.jar)
2. 源码构建:进入 Sentinel [Github 项目页面](https://github.com/alibaba/Sentinel),将代码 git clone 到本地自行编译打包,[参考此文档](https://github.com/alibaba/Sentinel/tree/2021.x/sentinel-dashboard)。
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 中添加基本配置信息
1. 增加配置,在应用的 `/src/main/resources/application.properties` 中添加基本配置信息
```
```properties
spring.application.name=sentinel-example
server.port=18083
spring.cloud.sentinel.transport.dashboard=localhost:8080
@ -84,48 +84,49 @@
2. 启动应用,支持 IDE 直接启动和编译打包后启动。
1. IDE直接启动找到主类 `ServiceApplication`,执行 main 方法启动应用。
2. 打包编译后启动:首先执行 `mvn clean package` 将工程编译打包,然后执行 `java -jar sentinel-core-example.jar`启动应用。
2. 打包编译后启动:首先执行 `mvn clean package` 将工程编译打包,然后执行 `java -jar sentinel-core-example.jar` 启动应用。
### 调用服务
使用 curl 分别调用两个 URL可以看到访问成功。
使用 curl 命令分别调用两个 URL可以看到访问成功。
<p align="center"><img src="https://cdn.yuque.com/lark/0/2018/png/54319/1532084640137-8f4bc16c-4336-4c1b-9ddd-4582b967717a.png" width="240" heigh='180' ></p>
```shell
$ curl http://localhost:18083/test
Blocked by Sentinel (flow limiting)
$ curl http://localhost:18083/hello
Hello
```
### 配置限流规则并验证
1. 访问 http://localhost:8080 页面,可以在左侧看到 Sentinel-Example 应用已经注册到了控制台,单击 **流控规则** ,可以看到目前的流控规则为空。
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)"。
如果需要自定义处理逻辑,实现的方式如下:
URL 限流触发后默认处理逻辑是,直接返回 "Blocked by Sentinel (flow limiting)"。 如果需要自定义处理逻辑,实现的方式如下:
```java
public class CustomUrlBlockHandler implements UrlBlockHandler {
@ -178,7 +179,7 @@ public final class ExceptionUtil {
## Endpoint 信息查看
Spring Boot 应用支持通过 Endpoint 来暴露相关信息,Sentinel Starter 也支持这一点。
Spring Boot 应用支持通过 Endpoint 来暴露相关信息,`spring-cloud-starter-alibaba-sentinel` 也支持这一点。
在使用之前需要在 Maven 中添加 `spring-boot-starter-actuator`依赖,并在配置中允许 Endpoints 的访问。
* Spring Boot 1.x 中添加配置 `management.security.enabled=false`
@ -218,16 +219,14 @@ spring.cloud.sentinel.datasource.ds2.nacos.data-type=json
其中`nacos``zk``apollo``redis` 这4种类型的使用需要加上对应的依赖`sentinel-datasource-nacos`, `sentinel-datasource-zookeeper`, `sentinel-datasource-apollo`, `sentinel-datasource-redis`
当ReadableDataSource加载规则数据成功的时候控制台会打印出相应的日志信息
`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 sentinel starter 有任何建议或想法,欢迎在 issue 中或者通过其他社区渠道向我们提出。
如果您对 `spring-cloud-starter-alibaba-sentinel` 有任何建议或想法,欢迎在 issue 中或者通过其他社区渠道向我们提出。

@ -14,48 +14,54 @@ Before we start the demo, let's learn how to connect Sentinel to a Spring Cloud
1. Add dependency spring-cloud-starter-alibaba-sentinel in the pom.xml file in your Spring Cloud project.
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
```xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
```
2. Define Resources
1. Define HTTP Resources
Sentinel starter 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.
`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.
@SentinelResource("resource")
public String hello() {
return "Hello";
}
```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.
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);
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.
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](http://edas-public.oss-cn-hangzhou.aliyuncs.com/install_package/demo/sentinel-dashboard.jar)
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/tree/2021.x/sentinel-dashboard) for details.
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).
@ -63,10 +69,12 @@ Before we start the demo, let's learn how to connect Sentinel to a Spring Cloud
### Start Application
1. Add necessary configurations to file `/src/main/resources/application.properties`.
spring.application.name=sentinel-example
server.port=18083
spring.cloud.sentinel.transport.dashboard=localhost:8080
```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.
@ -75,22 +83,23 @@ Before we start the demo, let's learn how to connect Sentinel to a Spring Cloud
### Invoke Service
Execute command `curl http://127.0.0.1:18083/hello`
Execute command `curl http://127.0.0.1:18083/test`
Use curl command to call two URLs, you can see:
The screenshot belows shows invoke success:
<p align="center"><img src="https://cdn.yuque.com/lark/0/2018/png/54319/1532084640137-8f4bc16c-4336-4c1b-9ddd-4582b967717a.png" width="240" heigh='180' ></p>
```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, and you can find a Sentinel-Example Application has been registered to the dashboard.
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>
@ -105,43 +114,57 @@ The screenshot belows shows invoke success:
<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)".
If you want to customize your flow control logic, see the code below:
public class CustomUrlBlockHandler implements UrlBlockHandler {
@Override
public void blocked(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws IOException {
// todo add your logic
}
}
WebCallbackManager.setUrlBlockHandler(new CustomUrlBlockHandler());
```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.
If you want to customize your flow control logic, implement interface `SentinelExceptionHandler`, set @SentinelResource's blockHandler() and blockHandlerClass(). See the code below:
@SentinelResource(value = "resource", blockHandler = "", blockHandlerClass = ExceptionUtil.class)
public String hello() {
return "Hello";
}
// ExceptionUtil.java
public class ExceptionUtil {
public static void handleException(BlockException ex) {
System.out.println("Oops: " + ex.getClass().getCanonicalName());
}
}
```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
@ -163,7 +186,7 @@ To view the endpoint information, visit the following URLS:
## Metrics
You can view metrics information on Sentinel Dashboard.
To see the metrics, click **实时监控(Real-time Monitoring)** in the left-side navigation pane.
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.
@ -193,8 +216,6 @@ Now ReadableDataSource type support 5 categories: `file`, `nacos`, `zk`, `apollo
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:
```

Loading…
Cancel
Save