持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第18天,点击查看活动详情
1 Sentinel初始化工程演示
- 启动Nacos8848成功
- 单机安装和启动:Spring Cloud Alibaba Nacos下载和安装
- 集群安装和启动:Nacos集群架构+Linux环境安装
- 创建新的Module:cloudalibaba-sentinel-service8401
- 启动Sentinel8080
- sentinel安装和启动:Sentinel介绍+安装
- 启动微服务8401
- 启动8401微服务后查看Sentinel控制台
2 搭建Sentinel项目
2.1 Sentinel的官方文档网址
2.2 创建项目
创建一个实验项目
cloudalibaba-sentinel-service8401
2.3 导入依赖
这里需要Nacos的依赖和sentinel的依赖
因为sentinel流控默认使用内存,如果不把流控规则放入nacos,sentinel重启后,需要再重新设置一遍
<!-- 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>
2.4 配置yaml文件
让当前8401注册进Nacos,然后被Sentinel8080进行监控
server:
port: 8401
spring:
application:
name: cloudalibaba-sentinel-service
cloud:
nacos:
discovery:
server-addr: localhost:8848
sentinel:
transport:
# 配置Sentinel dashboard地址,sentinel控制台
dashboard: localhost:8080
# sentinel客户端端口,默认8719端口,键入被占用会自动从8719+1,直到找到未被占用的端口
port: 8719
management:
endpoints:
web:
exposure:
include: '*'
2.5 编写FlowLimitController
@RestController
public class FlowLimitController {
@GetMapping("/testA")
public String testA(){
return "-----testA";
}
@GetMapping("/testB")
public String testB(){
return "-----testB";
}
}
3 测试
上面的工序做完之后就可以开始测试了,当Nacos和Sentinel都是启动完毕之后启动项目,这时进入sentinel的控制台,发现并没有出现监控的服务。
因为Sentinel本身采用的是懒加载机制,所以我们需要首先访问服务对应的接口,Sentinel才能工作。
我们访问对应的接口,并多刷新几遍,模拟多次请求。
http://localhost:8401/testA
http://localhost:8401/testB
这时可以查看Sentinel的dashboard,发现testA和testB都已被监控。