1.Sentinel简介 Sentinel 是什么? 随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。 Sentinel 具有以下特征:
丰富的应用场景:Sentinel 承接了阿里巴巴近 10 年的双十一大促流量的核心场景,例如秒杀(即突发流量控制在系统容量可以承受的范围)、消息削峰填谷、集群流量控制、实时熔断下游不可用应用等。
完备的实时监控:Sentinel 同时提供实时的监控功能。您可以在控制台中看到接入应用的单台机器秒级数据,甚至 500 台以下规模的集群的汇总运行情况。
广泛的开源生态:Sentinel 提供开箱即用的与其它开源框架/库的整合模块,例如与 Spring Cloud、Dubbo、gRPC 的整合。您只需要引入相应的依赖并进行简单的配置即可快速地接入 Sentinel。
完善的 SPI 扩展点:Sentinel 提供简单易用、完善的 SPI 扩展接口。您可以通过实现扩展接口来快速地定制逻辑。例如定制规则管理、适配动态数据源等。
2.Sentinel控制台
我们也可以从官网下载源代码,然后mvn编译打包https://github.com/alibaba/Sentinel
初始账号/密码:sentinel/sentinel
登录进去是空的,因为我们没有接入任何应用。
3.Sentinel接入应用
1.创建Spring Initializr子模块
2.引入sentinel依赖
1
2
3
4
5
6
7
8
9
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
```
3. 3.配置文件
server: port: 18080 spring: application: name: sentinel-core-example cloud: sentinel: transport: dashboard: 127.0.0.1:80801
2
3
4
5
6
7
8
9
10
11
12
13
14
15
4. 4.启动
启动服务时候,发现sentinel的控制端没有新的消息出现。原因是因为sentinel控制台是一个懒加载,只有当有流量的时候才会显示具有流量的应用。我们创建controller

默认情况下是根据url进行限流的,我们可以设置下流控


设置为1,说明我们每秒只能访问一次

5. 5.基于资源限流的我们使用注解:
@GetMapping(“/resource”) @SentinelResource(“/resource”) public String resource(){ return “Hello resource”; }1
2
3
4
### 4.重写基于URL的限流自定义输出
1. 1.自定义url限流处理器
public class DemoUrlBlockHandler implements UrlBlockHandler { @Override public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException { httpServletResponse.getWriter().println(“error url request”); } }1
2
2. 2.我们需要把自定义的DemoUrlBlockHandler添加到Sentinel限流配置中去
@Configuration public class SentinelConfig { @PostConstruct public void innit(){ WebCallbackManager.setUrlBlockHandler(new DemoUrlBlockHandler()); } }1
2
3
4
5
6
7
8
9
10
11
12
13
然后我们重启服务,重启服务时候,之前的监控信息会丢失,重新设置流控为0,然后请求,返回如下结果:

### 4.重写基于资源名称的限流自定义输出
通过blockHandler方法名,默认情况下,会找本类下的上面方法,返回值和目标方法一致,也是String,入参和请求的接口入参一致,但是会返回一个BlockException

对于每一个资源resource,我们不可能都单独写一个限流的方法,能不能统一写一个统一的类作为限流。blockHandlerClass ={ExceptionUtil.class} 使用上面 blockHandlerClass属性自定义一个ExceptionUtil
public class ExceptionUtil { public static String exHandler(BlockException ex) { return “exHandler error”; } } ```