继续学习SpringCloud Alibaba的Sentinel,这里测试Nacos的config功能,首先启动nacos服务。
启动sentinel-dashboard-1.8.3.jar服务
java -jar sentinel-dashboard-1.8.3.jar
一、创建cloudalibaba-sentinel-service8401工程
pom.xml
<!-- SpringCloud alibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- 后续做持久化用到 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
<!-- sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
application.yml
server:
port: 8401
spring:
application:
name: cloudalibaba-sentinel-service
cloud:
nacos:
discovery: #Nacos注册中心地址
server-addr: localhost:8848
sentinel:
transport: #dashboard地址
dashboard: localhost:8080
port: 8719 #默认端口,如果被占用则从8719依次+1扫描
datasource:
dsl:
nacos:
server-addr: localhost:8848
dataId: cloudalibaba-sentinel-service
groupId: DEFAULT_GROUP
data_type: json
rule-type: flow
management:
endpoints:
web:
exposure:
include: "*"
MainApp8401
@SpringBootApplication
@EnableDiscoveryClient
public class MainApp8401 {
public static void main(String[] args) {
SpringApplication.run(MainApp8401.class, args);
}
}
FlowLimitController
@RestController
@Slf4j
public class FlowLimitController {
@GetMapping("/testA")
public String testA(){
try {
TimeUnit.MILLISECONDS.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "---------testA";
}
@GetMapping("/testB")
public String testB(){
return "----------testB";
}
@GetMapping("/testD")
public String testD(){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
// log.info("testD 测试RT");
log.info("testD 异常比例");
int age = 10/0;
return "------testD";
}
@GetMapping("/testE")
public String testE(){
log.info("testD 测试异常数");
int age = 10/0;
return "------testD 测试异常数";
}
@GetMapping("/testHotKey")
@SentinelResource(value = "testHotKey",blockHandler = "deal_testHotKey")
public String testHotKey(@RequestParam(value = "p1",required = false) String p1,
@RequestParam(value = "p2", required = false) String p2) {
return "-------testHotKey";
}
public String deal_testHotKey(String p1, String p2,
BlockException exception){
return "----deal_testHotKey,o(╥﹏╥)o";
}
}
二、测试
1.访问http://localhost:8401/testA和http://localhost:8401/testB
发现已经监控到发送信息
2.测试流控规则,阈值类型选择QPS,单机阈值输入1
多次访问http://localhost:8401/testA,会报错
3.超过阈值限制,自定义fallback消息或者默认反馈内容
-----------------------------------未完待续