Sentinel 的使用
分为两个部分:
- 核心库(Java 客户端):不依赖任何框架/库,能够运行于 Java 8 及以上的版本的运行时环境,同时对 Dubbo / Spring Cloud 等框架也有较好的支持。
- 控制台(Dashboard):Dashboard 主要负责管理推送规则、监控、管理机器信息等。
Sentinel下载和安装:
https://github.com/alibaba/Sentinel/releases
启动步骤
-
前提:1. 启动 Sentinel 控制台需要 JDK 版本为 1.8 及以上版本。
2. 端口不能被占用 -
启动命令:
-
官方:
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.8.2.jar
(
-Dcsp.sentinel.dashboard.server=consoleIp:port
指定控制台地址和端口。) -
直接运行:
java -jar sentinel-dashboard-1.8.2.jar
(默认8080端口)
-
-
访问地址:localhost:8080
-
默认账号:sentinel 密码:sentinel
搭建Sentinel项目
注:此项目需和Nacos一起配套使用,相关源码地址为:https://download.csdn.net/download/m_lonel/85749921
-
创建项目sentinel-8401
-
导入依赖:
<!-- Nacos客户端依赖 --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <!-- sentinel依赖 --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency>
-
配置yml文件,目的是让当前8401注册进Nacos,然后被Sentinel8080进行监控
server: port: 8401 spring: application: name: cloudalibaba-sentinel-service cloud: nacos: discovery: server-addr: localhost:8848 sentinel: transport: # 配置Sentinel dashboard地址 dashboard: localhost:8080 # 默认8719端口,键入被占用会自动从8719+1,直到找到未被占用的端口 port: 8719 # 暴露所有端点 management: endpoints: web: exposure: include: '*'
-
编写LimitController
package com.sentinel.sentinel8401.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class LimitController { @GetMapping("/testA") public String testA(){ return "-----testA"; } @GetMapping("/testB") public String testB(){ return "-----testB"; } }
测试
首先保证Nacos和Sentinel都是启动状态,然后再来启动项目,按照我们的理解这个时候,就应该在Sentinel的dashboard上能体现出它监控的服务,但是此时并没有,原因是因为Sentinel本身采用的是懒加载机制,所以我们需要首先访问服务对应的接口,只有访问过一次的资源才会被监控。