update sentinel docs & refactor

pull/365/head
fangjian0423 6 years ago
parent 6080f09794
commit 0e8933e1f8

@ -100,7 +100,7 @@ spring:
### Feign 支持
Sentinel 适配了 https://github.com/OpenFeign/feign[Feign] 组件。如果想使用,除了引入 `sentinel-starter` 的依赖外还需要 3 个步骤:
Sentinel 适配了 https://github.com/OpenFeign/feign[Feign] 组件。如果想使用,除了引入 `sentinel-starter` 的依赖外还需要 2 个步骤:
* 配置文件打开 sentinel 对 feign 的支持:`feign.sentinel.enabled=true`
* 加入 `feign starter` 依赖触发 `sentinel starter` 的配置类生效:
@ -110,15 +110,8 @@ Sentinel 适配了 https://github.com/OpenFeign/feign[Feign] 组件。如果想
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
```
* `feign` 内部的 `loadbalance` 功能依赖 Netflix 的 `ribbon` 模块(如果不使用 `loadbalance` 功能可不引入)
```xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
```
这是一个 `FeignClient` 对应的接口
这是一个 `FeignClient` 的简单使用示例:
```java
@FeignClient(name = "service-provider", fallback = EchoServiceFallback.class, configuration = FeignConfiguration.class)
@ -142,12 +135,10 @@ class EchoServiceFallback implements EchoService {
}
```
NOTE: Feign 对应的接口中的资源名策略定义httpmethod:protocol://requesturl
NOTE: Feign 对应的接口中的资源名策略定义httpmethod:protocol://requesturl。`@FeignClient` 注解中的所有属性Sentinel 都做了兼容。
`EchoService` 接口中方法 `echo` 对应的资源名为 `GET:http://service-provider/echo/{str}`。
请注意:`@FeignClient` 注解中的所有属性Sentinel 都做了兼容。
### RestTemplate 支持
Spring Cloud Alibaba Sentinel 支持对 `RestTemplate` 的服务调用使用 Sentinel 进行保护,在构造 `RestTemplate` bean的时候需要加上 `@SentinelRestTemplate` 注解。
@ -160,14 +151,13 @@ public RestTemplate restTemplate() {
}
```
`@SentinelRestTemplate` 注解的参数支持限流(`blockHandler`, `blockHandlerClass`)和降级(`fallback`, `fallbackClass`)的处理。
`@SentinelRestTemplate` 注解的属性支持限流(`blockHandler`, `blockHandlerClass`)和降级(`fallback`, `fallbackClass`)的处理。
其中 `blockHandler` 或 `fallback` 对应的方法必须是对应 `blockHandlerClass` 或 `fallbackClass` 中的静态方法。
其中 `blockHandler` 或 `fallback` 属性对应的方法必须是对应 `blockHandlerClass` 或 `fallbackClass` 属性中的静态方法。
该注解对应的方法参数跟 `ClientHttpRequestInterceptor` 接口中的参数一致,并多出了一个 `BlockException` 参数,且返回值是 `ClientHttpResponse`。
被限流后如果不继续执行后面的 Http 请求拦截器,则可以通过 `SentinelClientHttpResponse` 的一个实例来自定义被限流后的返回值结果。
该方法的参数跟返回值跟 `org.springframework.http.client.ClientHttpRequestInterceptor#interceptor` 方法一致,其中参数多出了一个 `BlockException` 参数用于获取 Sentinel 捕获的异常。
比如上述 `ExceptionUtil` 的 `handleException` 方法对应的声明如下:
比如上述 `@SentinelRestTemplate` 注解中 `ExceptionUtil` 的 `handleException` 属性对应的方法声明如下:
```java
public class ExceptionUtil {
@ -177,7 +167,11 @@ public class ExceptionUtil {
}
```
`@SentinelRestTemplate` 注解的限流(`blockHandler`, `blockHandlerClass`)和降级(`fallback`, `fallbackClass`)不强制填写,当被 Sentinel 熔断后,会返回 `RestTemplate request block by sentinel` 信息,或者也可以填写对应的方法自行处理。
NOTE: 应用启动的时候会检查 `@SentinelRestTemplate` 注解对应的限流或降级方法是否存在,如不存在会抛出异常
`@SentinelRestTemplate` 注解的限流(`blockHandler`, `blockHandlerClass`)和降级(`fallback`, `fallbackClass`)属性不强制填写。
当使用 `RestTemplate` 调用被 Sentinel 熔断后,会返回 `RestTemplate request block by sentinel` 信息,或者也可以编写对应的方法自行处理返回信息。这里提供了 `SentinelClientHttpResponse` 用于构造返回信息。
Sentinel RestTemplate 限流的资源规则提供两种粒度:
@ -189,98 +183,45 @@ NOTE: 以 `https://www.taobao.com/test` 这个 url 为例。对应的资源名
### 动态数据源支持
#### 在我们的第一个版本 0.2.0.RELEASE 或 0.1.0.RELEASE 中的使用方式
需要3个步骤才可完成数据源的配置
* 配置文件中定义数据源信息。比如使用文件:
.application.properties
----
spring.cloud.sentinel.datasource.type=file
spring.cloud.sentinel.datasource.recommendRefreshMs=3000
spring.cloud.sentinel.datasource.bufSize=4056196
spring.cloud.sentinel.datasource.charset=utf-8
spring.cloud.sentinel.datasource.converter=flowConverter
spring.cloud.sentinel.datasource.file=/Users/you/yourrule.json
----
* 创建一个 Converter 类实现 `com.alibaba.csp.sentinel.datasource.Converter` 接口,并且需要在 `ApplicationContext` 中有该类的一个 Bean
```java
@Component("flowConverter")
public class JsonFlowRuleListParser implements Converter<String, List<FlowRule>> {
@Override
public List<FlowRule> convert(String source) {
return JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
});
}
}
```
这个 Converter 的 bean name 需要跟 `application.properties` 配置文件中的 converter 配置一致
* 在任意一个 Spring Bean 中定义一个被 `@SentinelDataSource` 注解修饰的 `ReadableDataSource` 属性
```java
@SentinelDataSource("spring.cloud.sentinel.datasource")
private ReadableDataSource dataSource;
```
`@SentinelDataSource` 注解的 value 属性表示数据源在 `application.properties` 配置文件中前缀。 该在例子中,前缀为 `spring.cloud.sentinel.datasource` 。
`SentinelProperties` 内部提供了 `TreeMap` 类型的 `datasource` 属性用于配置数据源信息。
如果 `ApplicationContext` 中存在超过1个 `ReadableDataSource` bean那么不会加载这些 `ReadableDataSource` 中的任意一个。 只有在 `ApplicationContext` 存在一个 `ReadableDataSource` 的情况下才会生效。
如果数据源生效并且规则成功加载,控制台会打印类似如下信息:
```
[Sentinel Starter] load 3 flow rules
```
#### 后续版本的使用方式
只需要1个步骤就可完成数据源的配置
* 直接在 `application.properties` 配置文件中配置数据源信息即可
比如配置了4个数据源
比如配置 4 个数据源:
```
spring.cloud.sentinel.datasource.ds1.file.file=classpath: degraderule.json
spring.cloud.sentinel.datasource.ds1.file.rule-type=flow
#spring.cloud.sentinel.datasource.ds1.file.file=classpath: flowrule.json
#spring.cloud.sentinel.datasource.ds1.file.data-type=custom
#spring.cloud.sentinel.datasource.ds1.file.converter-class=org.springframework.cloud.alibaba.cloud.examples.JsonFlowRuleListConverter
#spring.cloud.sentinel.datasource.ds1.file.rule-type=flow
spring.cloud.sentinel.datasource.ds2.nacos.server-addr=localhost: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
spring.cloud.sentinel.datasource.ds2.nacos.rule-type=degrade
spring.cloud.sentinel.datasource.ds3.zk.path = /Sentinel-Demo/SYSTEM-CODE-DEMO-FLOW
spring.cloud.sentinel.datasource.ds3.zk.server-addr = localhost:2181
spring.cloud.sentinel.datasource.ds3.zk.rule-type=authority
spring.cloud.sentinel.datasource.ds4.apollo.namespace-name = application
spring.cloud.sentinel.datasource.ds4.apollo.flow-rules-key = sentinel
spring.cloud.sentinel.datasource.ds4.apollo.default-flow-rule-value = test
spring.cloud.sentinel.datasource.ds5.apollo.rule-type=param-flow
```
这样配置方式参考了 Spring Cloud Stream Binder 的配置,内部使用了 `TreeMap` 进行存储comparator 为 `String.CASE_INSENSITIVE_ORDER` 。
NOTE: d1, ds2, ds3, ds4 是 `ReadableDataSource` 的名字,可随意编写。后面的 `file` `zk` `nacos` , `apollo` 就是对应具体的数据源。 它们后面的配置就是这些数据源各自的配置。
每种数据源都有两个共同的配置项: `data-type` 和 `converter-class` 。
`data-type` 配置项表示 `Converter`Spring Cloud Alibaba Sentinel 默认提供两种内置的值,分别是 `json` 和 `xml` (不填默认是json)。 如果不想使用内置的 `json` 或 `xml` 这两种 `Converter`,可以填写 `custom` 表示自定义 `Converter`,然后再配置 `converter-class` 配置项,该配置项需要写类的全路径名。
这种配置方式参考了 Spring Cloud Stream Binder 的配置,内部使用了 `TreeMap` 进行存储comparator 为 `String.CASE_INSENSITIVE_ORDER` 。
这两种内置的 `Converter` 只支持解析 json 数组 或 xml 数组。内部解析的时候会自动判断每个 json 对象或xml对象属于哪4种 Sentinel 规则(`FlowRule``DegradeRule``SystemRule``AuthorityRule`, `ParamFlowRule`)
NOTE: d1, ds2, ds3, ds4 是 `ReadableDataSource` 的名字,可随意编写。后面的 `file` `zk` `nacos` , `apollo` 就是对应具体的数据源。 它们后面的配置就是这些具体数据源各自的配置。
比如10个规则数组里解析出5个限流规则和5个降级规则。 这种情况下该数据源不会注册,日志里页会进行警告
每种数据源都有两个共同的配置项: `data-type`、 `converter-class` 以及 `rule-type`。
如果10个规则里有9个限流规则1个解析报错了。这种情况下日志会警告有个规则格式错误另外9个限流规则会注册上去
`data-type` 配置项表示 `Converter` 类型Spring Cloud Alibaba Sentinel 默认提供两种内置的值,分别是 `json` 和 `xml` (不填默认是json)。 如果不想使用内置的 `json` 或 `xml` 这两种 `Converter`,可以填写 `custom` 表示自定义 `Converter`,然后再配置 `converter-class` 配置项,该配置项需要写类的全路径名(比如 `spring.cloud.sentinel.datasource.ds1.file.converter-class=org.springframework.cloud.alibaba.cloud.examples.JsonFlowRuleListConverter`)。
这里 json 或 xml 解析用的是 `jackson`。`ObjectMapper` 或 `XmlMapper` 使用默认的配置,遇到不认识的字段会解析报错。 因为不这样做的话限流 json 也会解析成 系统规则(系统规则所有的配置都有默认值),所以需要这样严格解析。
当然还有一种情况是 json 对象或 xml 对象可能会匹配上所有4种规则(比如json对象里只配了 `resource` 字段那么会匹配上4种规则),这种情况下日志里会警告,并且过滤掉这个对象。
用户使用这种配置的时候只需要填写正确的json或xml就行有任何不合理的信息都会在日志里打印出来。
`rule-type` 配置表示该数据源中的规则属于哪种类型的规则(`flow``degrade``authority``system`, `param-flow`)。
如果数据源生效并且规则成功加载,控制台会打印类似如下信息:
@ -289,6 +230,8 @@ NOTE: d1, ds2, ds3, ds4 是 `ReadableDataSource` 的名字,可随意编写。
[Sentinel Starter] DataSource ds2-sentinel-nacos-datasource load 2 FlowRule
```
NOTE: 当某个数据源规则信息加载失败的情况下,不会影响应用的启动,会在日志中打印出错误信息。
NOTE: 默认情况下xml 格式是不支持的。需要添加 `jackson-dataformat-xml` 依赖后才会自动生效。
关于 Sentinel 动态数据源的实现原理,参考: https://github.com/alibaba/Sentinel/wiki/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%99%E6%89%A9%E5%B1%95[动态规则扩展]
@ -300,6 +243,8 @@ NOTE: 默认情况下xml 格式是不支持的。需要添加 `jackson-datafo
* Spring Boot 1.x 中添加配置 `management.security.enabled=false`。暴露的 endpoint 路径为 `/sentinel`
* Spring Boot 2.x 中添加配置 `management.endpoints.web.exposure.include=*`。暴露的 endpoint 路径为 `/actuator/sentinel`
Sentinel Endpoint 里暴露的信息非常有用。包括当前应用的所有规则信息、日志目录、当前实例的 IPSentinel Dashboard 地址Block Page应用与 Sentinel Dashboard 的心跳频率等等信息。
### More
下表显示当应用的 `ApplicationContext` 中存在对应的Bean的类型时会进行的一些操作
@ -310,6 +255,7 @@ NOTE: 默认情况下xml 格式是不支持的。需要添加 `jackson-datafo
^|存在Bean的类型 ^|操作 ^|作用
|`UrlCleaner`|`WebCallbackManager.setUrlCleaner(urlCleaner)`|资源清理(资源(比如将满足 /foo/:id 的 URL 都归到 /foo/* 资源下))
|`UrlBlockHandler`|`WebCallbackManager.setUrlBlockHandler(urlBlockHandler)`|自定义限流处理逻辑
|`RequestOriginParser`|`WebCallbackManager.setRequestOriginParser(requestOriginParser)`|设置来源信息
|====
下表显示 Spring Cloud Alibaba Sentinel 的所有配置信息:
@ -322,14 +268,17 @@ NOTE: 默认情况下xml 格式是不支持的。需要添加 `jackson-datafo
|`spring.cloud.sentinel.eager`|取消Sentinel控制台懒加载|false
|`spring.cloud.sentinel.transport.port`|应用与Sentinel控制台交互的端口应用本地会起一个该端口占用的HttpServer|8721
|`spring.cloud.sentinel.transport.dashboard`|Sentinel 控制台地址|
|`spring.cloud.sentinel.transport.heartbeatIntervalMs`|应用与Sentinel控制台的心跳间隔时间|
|`spring.cloud.sentinel.transport.heartbeat-interval-ms`|应用与Sentinel控制台的心跳间隔时间|
|`spring.cloud.sentinel.transport.client-ip`|客户端IP|
|`spring.cloud.sentinel.filter.order`|Servlet Filter的加载顺序。Starter内部会构造这个filter|Integer.MIN_VALUE
|`spring.cloud.sentinel.filter.spring.url-patterns`|数据类型是数组。表示Servlet Filter的url pattern集合|/*
|`spring.cloud.sentinel.filter.url-patterns`|数据类型是数组。表示Servlet Filter的url pattern集合|/*
|`spring.cloud.sentinel.metric.charset`|metric文件字符集|UTF-8
|`spring.cloud.sentinel.metric.fileSingleSize`|Sentinel metric 单个文件的大小|
|`spring.cloud.sentinel.metric.fileTotalCount`|Sentinel metric 总文件数量|
|`spring.cloud.sentinel.metric.file-single-size`|Sentinel metric 单个文件的大小|
|`spring.cloud.sentinel.metric.file-total-count`|Sentinel metric 总文件数量|
|`spring.cloud.sentinel.log.dir`|Sentinel 日志文件所在的目录|
|`spring.cloud.sentinel.log.switch-pid`|Sentinel 日志文件名是否需要带上pid|false
|`spring.cloud.sentinel.servlet.blockPage`| 自定义的跳转 URL当请求被限流时会自动跳转至设定好的 URL |
|`spring.cloud.sentinel.flow.coldFactor`| https://github.com/alibaba/Sentinel/wiki/%E9%99%90%E6%B5%81---%E5%86%B7%E5%90%AF%E5%8A%A8[冷启动因子] |3
|`spring.cloud.sentinel.servlet.block-page`| 自定义的跳转 URL当请求被限流时会自动跳转至设定好的 URL |
|`spring.cloud.sentinel.flow.cold-factor`| https://github.com/alibaba/Sentinel/wiki/%E9%99%90%E6%B5%81---%E5%86%B7%E5%90%AF%E5%8A%A8[冷启动因子] |3
|====
NOTE: 请注意。这些配置只有在 Servlet 环境下才会生效RestTemplate 和 Feign 针对这些配置都无法生效

@ -100,7 +100,7 @@ For more information about Sentinel dashboard, please refer to https://github.co
### Feign Support
Sentinel is compatible with the https://github.com/OpenFeign/feign[Feign] component. To use it, in addition to introducing the `sentinel-starter` dependency, complete the following 3 steps:
Sentinel is compatible with the https://github.com/OpenFeign/feign[Feign] component. To use it, in addition to introducing the `sentinel-starter` dependency, complete the following 2 steps:
* Enable the Sentinel support for feign in the properties file. `feign.sentinel.enabled=true`
* Add the `feign starter` dependency to trigger and enable `sentinel starter`:
@ -110,15 +110,8 @@ Sentinel is compatible with the https://github.com/OpenFeign/feign[Feign] compon
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
```
* The `loadbalance` in `feign` is dependent on the `ribbon` module of Netflix (You do not need to introduce it if `loadbalance` is not used)
```xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
```
This is an interface for `FeignClient`:
This is a simple usage of `FeignClient`:
```java
@FeignClient(name = "service-provider", fallback = EchoServiceFallback.class, configuration = FeignConfiguration.class)
@ -142,12 +135,10 @@ class EchoServiceFallback implements EchoService {
}
```
NOTE: The resource name policy in the corresponding interface of Feign ishttpmethod:protocol://requesturl
NOTE: The resource name policy in the corresponding interface of Feign ishttpmethod:protocol://requesturl. All the attributes in the `@FeignClient` annotation is supported by Sentinel.
The corresponding resource name of the `echo` method in the `EchoService` interface is `GET:http://service-provider/echo/{str}`.
Note: All the attributes in the `@FeignClient` annotation is supported by Sentinel.
### RestTemplate Support
Spring Cloud Alibaba Sentinel supports the protection of `RestTemplate` service calls using Sentinel. To do this, you need to add the `@SentinelRestTemplate` annotation when constructing the `RestTemplate` bean.
@ -160,14 +151,13 @@ public RestTemplate restTemplate() {
}
```
The parameter of the `@SentinelRestTemplate` annotation support flow control(`blockHandler`, `blockHandlerClass`) and circuit breaking(`fallback`, `fallbackClass`).
The attribute of the `@SentinelRestTemplate` annotation support flow control(`blockHandler`, `blockHandlerClass`) and circuit breaking(`fallback`, `fallbackClass`).
==
The `blockHandler` or `fallback` is the static method of `blockHandlerClass` or `fallbackClass`.
The parameter of method in `@SentinelRestTemplate` is same as `ClientHttpRequestInterceptor`, but it has one more parameter `BlockException` and its value of return type should be `ClientHttpResponse`.
If you do not continue to execute the following Http request interceptor after being restricted, you can use the instance of `SentinelClientHttpResponse` to customize the return value result after the current limit.
The parameter and return value of method in `@SentinelRestTemplate` is same as `org.springframework.http.client.ClientHttpRequestInterceptor#interceptor`, but it has one more parameter `BlockException` to catch the exception by Sentinel.
The method signature of `handleException` in `ExceptionUtil` above should be like this:
@ -179,7 +169,11 @@ public class ExceptionUtil {
}
```
It will return `RestTemplate request block by sentinel` when you do not write any flow control(`blockHandler`, `blockHandlerClass`) configuration or circuit breaking configuration(`fallback`, `fallbackClass`), you can override it by using your own method.
NOTE: When the application starts, it will check if the `@SentinelRestTemplate` annotation corresponding to the flow control or circuit breaking method exists, if it does not exist, it will throw an exception.
The attribute of the `@SentinelRestTemplate` annotation is optional.
It will return `RestTemplate request block by sentinel` when you using `RestTemplate` blocked by Sentinel. You can override it by your own logic. We provide `SentinelClientHttpResponse` to handle the response.
Sentinel RestTemplate provides two granularities for resource rate limiting:
@ -191,98 +185,44 @@ NOTE: Take `https://www.taobao.com/test` as an example. The corresponding resour
### Dynamic Data Source Support
#### The usage of our first version 0.2.0.RELEASE or 0.1.0.RELEASE
you need to complete the following 3 steps to configure your data source.
* Define the data source information in your properties file. For example, you can use:
.application.properties
----
spring.cloud.sentinel.datasource.type=file
spring.cloud.sentinel.datasource.recommendRefreshMs=3000
spring.cloud.sentinel.datasource.bufSize=4056196
spring.cloud.sentinel.datasource.charset=utf-8
spring.cloud.sentinel.datasource.converter=flowConverter
spring.cloud.sentinel.datasource.file=/Users/you/yourrule.json
----
* Create a Converter class to implement the `com.alibaba.csp.sentinel.datasource.Converter` interface, and you need to have a bean of this class in `ApplicationContext`.
```java
@Component("flowConverter")
public class JsonFlowRuleListParser implements Converter<String, List<FlowRule>> {
@Override
public List<FlowRule> convert(String source) {
return JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
});
}
}
```
The bean name of this Converter needs to be the same with the converter in the `application.properties` file.
* Define a `ReadableDataSource` attribute that is modified by the `@SentinelDataSource` annotation in any Spring Bean `@SentinelDataSource`.
```java
@SentinelDataSource("spring.cloud.sentinel.datasource")
private ReadableDataSource dataSource;
```
The value attribute of `@SentinelDataSource` means that the data source is in the prefix of the `application.properties` file. In this example, the prefix is `spring.cloud.sentinel.datasource`.
If there are over 1 `ReadableDataSource` beans in `ApplicationContext`, then none of the data sources in `ReadableDataSource` will be loaded. It takes effect only when there is only 1 `ReadableDataSource` in `ApplicationContext`.
If the data source takes effect and is loaded successfully, the dashboard will print information as shown below:
```
[Sentinel Starter] load 3 flow rules
```
#### The usage after first version
You only need to complete 1 step to configure your data source:
* Configure your data source in the `application.properties` file directly.
`SentinelProperties` provide `datasource` attribute to configure datasource.
For example, 4 data sources are configures
```
spring.cloud.sentinel.datasource.ds1.file.file=classpath: degraderule.json
spring.cloud.sentinel.datasource.ds1.file.rule-type=flow
#spring.cloud.sentinel.datasource.ds1.file.file=classpath: flowrule.json
#spring.cloud.sentinel.datasource.ds1.file.data-type=custom
#spring.cloud.sentinel.datasource.ds1.file.converter-class=org.springframework.cloud.alibaba.cloud.examples.JsonFlowRuleListConverter
#spring.cloud.sentinel.datasource.ds1.file.rule-type=flow
spring.cloud.sentinel.datasource.ds2.nacos.server-addr=localhost: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
spring.cloud.sentinel.datasource.ds2.nacos.rule-type=degrade
spring.cloud.sentinel.datasource.ds3.zk.path = /Sentinel-Demo/SYSTEM-CODE-DEMO-FLOW
spring.cloud.sentinel.datasource.ds3.zk.server-addr = localhost:2181
spring.cloud.sentinel.datasource.ds3.zk.rule-type=authority
spring.cloud.sentinel.datasource.ds4.apollo.namespace-name = application
spring.cloud.sentinel.datasource.ds4.apollo.flow-rules-key = sentinel
spring.cloud.sentinel.datasource.ds4.apollo.default-flow-rule-value = test
spring.cloud.sentinel.datasource.ds5.apollo.rule-type=param-flow
```
This method follows the configuration of Spring Cloud Stream Binder. `TreeMap` is used for storage internally, and comparator is `String.CASE_INSENSITIVE_ORDER`.
NOTE: d1, ds2, ds3, ds4 are the names of `ReadableDataSource`, and can be coded as you like. The `file`, `zk`, `nacos` , `apollo` refer to the specific data sources. The configurations following them are the specific configurations of these data sources respecitively.
Every data source has two common configuration items: `data-type` and `converter-class`.
`data-type` refers to `Converter`. Spring Cloud Alibaba Sentinel provides two embedded values by defaul: `json` and `xml` (the default is json if not specified). If you do not want to use the embedded `json` or `xml` `Converter`, you can also fill in `custom` to indicate that you will define your own `Converter`, and then configure the `converter-class`. You need to specify the full path of the class for this configuration.
The two embedded `Converter` only supports parsing the Json array or XML array. Sentinel will determine automatically which of the 4 Sentinel rules that the Json or XML objext belongs to(`FlowRule`, `DegradeRule`, `SystemRule`, `AuthorityRule`, `ParamFlowRule`).
Every data source has 3 common configuration items: `data-type`, `converter-class` and `rule-type`.
For example, if 5 rate limiting rules and 5 degradation rules in the 10 rule arrays, then the data source will not be registered, and there will be warnings in the logs.
`data-type` refers to `Converter`. Spring Cloud Alibaba Sentinel provides two embedded values by default: `json` and `xml` (the default is json if not specified). If you do not want to use the embedded `json` or `xml` `Converter`, you can also fill in `custom` to indicate that you will define your own `Converter`, and then configure the `converter-class`. You need to specify the full path of the class for this configuration.
If there are 9 rate limiting rules among the 10 arrays, and 1 error parsing the 10th array, then there will be warning in the log indicating that there is error in one of the rules, while the other 9 rules will be registered.
Here `jackson` is used to parse the Json or XML arrays. `ObjectMapper` or `XmlMapper` uses the default configuration and will report error if there are unrecognized fields. The reason behind this logic is that without this strict parsing, Json will also be parsed as system rules(all system rules have default values).
In another case, the Json or XML object might match all of the 4 rules(for example, if only the `resource` field is configured in the Json object, then it will match all 4 rules). In this case, there will be warnings in the log, and this object will be filtered.
When you use this configuration, you only need to fill in the Json or XML correctly, and any of the unreasonable information will be printed in the log.
`rule-type` refers to the rule type in datasource(`flow`, `degrade`, `authority`, `system`, `param-flow`).
If the data source takes effect and is loaded successfully, the dashboard will print information as shown below:
@ -302,6 +242,8 @@ Before you use the Endpoint feature, please add the `spring-boot-starter-actuat
* Add `management.security.enabled=false` in Spring Boot 1.x. The exposed endpoint path is `/sentinel`.
* Add `management.endpoints.web.exposure.include=*` in Spring Boot 2.x. The exposed endpoint path is `/actuator/sentinel`.
The information exposed in Sentinel Endpoint is very useful. It includes all the rules of the current application, the log directory, the IP of the current instance, the Sentinel Dashboard address, the Block Page, the heartbeat frequency of the application and the Sentinel Dashboard, and so on.
### More
The following table shows that when there are corresponding bean types in `ApplicationContext`, some actions will be taken:
@ -312,6 +254,7 @@ The following table shows that when there are corresponding bean types in `Appli
^|Existing Bean Type ^|Action ^|Function
|`UrlCleaner`|`WebCallbackManager.setUrlCleaner(urlCleaner)`|Resource cleaning(resource(for example, classify all URLs of /foo/:id to the /foo/* resource))
|`UrlBlockHandler`|`WebCallbackManager.setUrlBlockHandler(urlBlockHandler)`|Customize rate limiting logic
|`RequestOriginParser`|`WebCallbackManager.setRequestOriginParser(requestOriginParser)`|Setting the origin
|====
The following table shows all the configurations of Spring Cloud Alibaba Sentinel:
@ -325,13 +268,16 @@ The following table shows all the configurations of Spring Cloud Alibaba Sentine
|`spring.cloud.sentinel.transport.port`|Port for the application to interact with Sentinel dashboard. An HTTP Server which uses this port will be started in the application|8721
|`spring.cloud.sentinel.transport.dashboard`|Sentinel dashboard address|
|`spring.cloud.sentinel.transport.heartbeatIntervalMs`|Hearbeat interval between the application and Sentinel dashboard|
|`spring.cloud.sentinel.transport.client-ip`|Client IP|
|`spring.cloud.sentinel.filter.order`|Loading order of Servlet Filter. The filter will be constructed in the Starter|Integer.MIN_VALUE
|`spring.cloud.sentinel.filter.spring.url-patterns`|Data type is array. Refers to the collection of Servlet Filter ULR patterns|/*
|`spring.cloud.sentinel.filter.url-patterns`|Data type is array. Refers to the collection of Servlet Filter ULR patterns|/*
|`spring.cloud.sentinel.metric.charset`|metric file character set|UTF-8
|`spring.cloud.sentinel.metric.fileSingleSize`|Sentinel metric single file size|
|`spring.cloud.sentinel.metric.fileTotalCount`|Sentinel metric total file number|
|`spring.cloud.sentinel.log.dir`|Directory of Sentinel log files|
|`spring.cloud.sentinel.log.switch-pid`|If PID is required for Sentinel log file names|false
|`spring.cloud.sentinel.servlet.blockPage`| Customized redirection URL. When rate limited, the request will be redirected to the pre-defined URL |
|`spring.cloud.sentinel.flow.coldFactor`| https://github.com/alibaba/Sentinel/wiki/%E9%99%90%E6%B5%81---%E5%86%B7%E5%90%AF%E5%8A%A8[冷启动因子] |3
|`spring.cloud.sentinel.flow.coldFactor`| https://github.com/alibaba/Sentinel/wiki/%E9%99%90%E6%B5%81---%E5%86%B7%E5%90%AF%E5%8A%A8[ColdFactor] |3
|====
NOTE: These configurations will only take effect in servlet environment. RestTemplate and Feign will not take effect for these configurations.

@ -38,7 +38,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
public abstract class SentinelConverter<T extends AbstractRule>
implements Converter<String, List<AbstractRule>> {
private static final Logger logger = LoggerFactory.getLogger(SentinelConverter.class);
private static final Logger log = LoggerFactory.getLogger(SentinelConverter.class);
private final ObjectMapper objectMapper;
@ -53,7 +53,7 @@ public abstract class SentinelConverter<T extends AbstractRule>
public List<AbstractRule> convert(String source) {
List<AbstractRule> ruleList = new ArrayList<>();
if (StringUtils.isEmpty(source)) {
logger.warn("converter can not convert rules because source is empty");
log.warn("converter can not convert rules because source is empty");
return ruleList;
}
try {

@ -16,7 +16,11 @@
package org.springframework.cloud.alibaba.sentinel;
import com.alibaba.csp.sentinel.adapter.servlet.CommonFilter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.Filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -27,9 +31,7 @@ import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.Filter;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.csp.sentinel.adapter.servlet.CommonFilter;
/**
* @author xiaojing
@ -40,7 +42,7 @@ import java.util.List;
@EnableConfigurationProperties(SentinelProperties.class)
public class SentinelWebAutoConfiguration {
private static final Logger logger = LoggerFactory
private static final Logger log = LoggerFactory
.getLogger(SentinelWebAutoConfiguration.class);
@Autowired
@ -63,7 +65,7 @@ public class SentinelWebAutoConfiguration {
Filter filter = new CommonFilter();
registration.setFilter(filter);
registration.setOrder(filterConfig.getOrder());
logger.info("[Sentinel Starter] register Sentinel with urlPatterns: {}.",
log.info("[Sentinel Starter] register Sentinel with urlPatterns: {}.",
filterConfig.getUrlPatterns());
return registration;

@ -16,7 +16,10 @@
package org.springframework.cloud.alibaba.sentinel.custom;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
@ -37,9 +40,7 @@ import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
import com.alibaba.csp.sentinel.slots.block.BlockException;
/**
* PostProcessor handle @SentinelRestTemplate Annotation, add interceptor for RestTemplate
@ -50,7 +51,7 @@ import java.util.concurrent.ConcurrentHashMap;
*/
public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProcessor {
private static final Logger logger = LoggerFactory
private static final Logger log = LoggerFactory
.getLogger(SentinelBeanPostProcessor.class);
private final ApplicationContext applicationContext;
@ -97,14 +98,14 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces
return;
}
if (blockClass != void.class && StringUtils.isEmpty(blockMethod)) {
logger.error(
log.error(
"{} class attribute exists but {} method attribute is not exists in bean[{}]",
type, type, beanName);
throw new IllegalArgumentException(type + " class attribute exists but "
+ type + " method attribute is not exists in bean[" + beanName + "]");
}
else if (blockClass == void.class && !StringUtils.isEmpty(blockMethod)) {
logger.error(
log.error(
"{} method attribute exists but {} class attribute is not exists in bean[{}]",
type, type, beanName);
throw new IllegalArgumentException(type + " method attribute exists but "
@ -116,7 +117,7 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces
Arrays.stream(args).map(clazz -> clazz.getSimpleName()).toArray());
Method foundMethod = ClassUtils.getStaticMethod(blockClass, blockMethod, args);
if (foundMethod == null) {
logger.error(
log.error(
"{} static method can not be found in bean[{}]. The right method signature is {}#{}{}, please check your class name, method name and arguments",
type, beanName, blockClass.getName(), blockMethod, argsStr);
throw new IllegalArgumentException(type
@ -127,7 +128,7 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces
}
if (!ClientHttpResponse.class.isAssignableFrom(foundMethod.getReturnType())) {
logger.error(
log.error(
"{} method return value in bean[{}] is not ClientHttpResponse: {}#{}{}",
type, beanName, blockClass.getName(), blockMethod, argsStr);
throw new IllegalArgumentException(type + " method return value in bean["

@ -36,7 +36,7 @@ import com.alibaba.csp.sentinel.slots.block.AbstractRule;
*/
public class SentinelDataSourceHandler implements SmartInitializingSingleton {
private static final Logger logger = LoggerFactory
private static final Logger log = LoggerFactory
.getLogger(SentinelDataSourceHandler.class);
private List<String> dataTypeList = Arrays.asList("json", "xml");
@ -61,7 +61,7 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton {
try {
List<String> validFields = dataSourceProperties.getValidField();
if (validFields.size() != 1) {
logger.error("[Sentinel Starter] DataSource " + dataSourceName
log.error("[Sentinel Starter] DataSource " + dataSourceName
+ " multi datasource active and won't loaded: "
+ dataSourceProperties.getValidField());
return;
@ -73,7 +73,7 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton {
+ "-sentinel-" + validFields.get(0) + "-datasource");
}
catch (Exception e) {
logger.error("[Sentinel Starter] DataSource " + dataSourceName
log.error("[Sentinel Starter] DataSource " + dataSourceName
+ " build error: " + e.getMessage(), e);
}
});
@ -90,7 +90,7 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton {
m.put(v.getName(), v.get(dataSourceProperties));
}
catch (IllegalAccessException e) {
logger.error("[Sentinel Starter] DataSource " + dataSourceName
log.error("[Sentinel Starter] DataSource " + dataSourceName
+ " field: " + v.getName() + " invoke error");
throw new RuntimeException(
"[Sentinel Starter] DataSource " + dataSourceName
@ -136,7 +136,7 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton {
builder.addPropertyReference("converter", customConvertBeanName);
}
catch (ClassNotFoundException e) {
logger.error("[Sentinel Starter] DataSource " + dataSourceName
log.error("[Sentinel Starter] DataSource " + dataSourceName
+ " handle "
+ dataSourceProperties.getClass().getSimpleName()
+ " error, class name: "
@ -195,20 +195,20 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton {
ruleConfig = dataSource.loadConfig();
}
catch (Exception e) {
logger.error("[Sentinel Starter] DataSource " + dataSourceName
log.error("[Sentinel Starter] DataSource " + dataSourceName
+ " loadConfig error: " + e.getMessage(), e);
return;
}
if (ruleConfig instanceof List) {
List convertedRuleList = (List) ruleConfig;
if (CollectionUtils.isEmpty(convertedRuleList)) {
logger.warn("[Sentinel Starter] DataSource {} rule list is empty.",
log.warn("[Sentinel Starter] DataSource {} rule list is empty.",
dataSourceName);
return;
}
if (convertedRuleList.stream()
.noneMatch(rule -> rule.getClass() == ruleClass)) {
logger.error("[Sentinel Starter] DataSource {} none rules are {} type.",
log.error("[Sentinel Starter] DataSource {} none rules are {} type.",
dataSourceName, ruleClass.getSimpleName());
throw new IllegalArgumentException("[Sentinel Starter] DataSource "
+ dataSourceName + " none rules are " + ruleClass.getSimpleName()
@ -216,16 +216,16 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton {
}
else if (!convertedRuleList.stream()
.allMatch(rule -> rule.getClass() == ruleClass)) {
logger.warn("[Sentinel Starter] DataSource {} all rules are not {} type.",
log.warn("[Sentinel Starter] DataSource {} all rules are not {} type.",
dataSourceName, ruleClass.getSimpleName());
}
else {
logger.info("[Sentinel Starter] DataSource {} load {} {}", dataSourceName,
log.info("[Sentinel Starter] DataSource {} load {} {}", dataSourceName,
convertedRuleList.size(), ruleClass.getSimpleName());
}
}
else {
logger.error("[Sentinel Starter] DataSource " + dataSourceName
log.error("[Sentinel Starter] DataSource " + dataSourceName
+ " rule class is not List<" + ruleClass.getSimpleName()
+ ">. Class: " + ruleConfig.getClass());
throw new IllegalArgumentException("[Sentinel Starter] DataSource "

@ -16,14 +16,11 @@
package org.springframework.cloud.alibaba.sentinel.custom;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import org.springframework.cloud.alibaba.sentinel.annotation.SentinelRestTemplate;
import org.springframework.cloud.alibaba.sentinel.rest.SentinelClientHttpResponse;
import org.springframework.http.HttpRequest;
@ -31,10 +28,12 @@ import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
/**
* Interceptor using by SentinelRestTemplate
@ -43,9 +42,6 @@ import java.net.URI;
*/
public class SentinelProtectInterceptor implements ClientHttpRequestInterceptor {
private static final Logger logger = LoggerFactory
.getLogger(SentinelProtectInterceptor.class);
private final SentinelRestTemplate sentinelRestTemplate;
public SentinelProtectInterceptor(SentinelRestTemplate sentinelRestTemplate) {

Loading…
Cancel
Save