目录
以上操作都是在8401微服务执行的
搭建工程
首先启动Nacos和Sentinel成功!!!
在8401加上依赖:
<dependency>
<groupId>com.atguigu.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
yml
server:
port: 8401
spring:
application:
name: cloudalibaba-sentinel-service
cloud:
nacos:
discovery:
server-addr: localhost:8848
sentinel:
transport:
dashboard: localhost:8080
port: 8719 #默认8719,假如被占用了会自动从8719开始依次+1扫描。直至找到未被占用的端口
management:
endpoints:
web:
exposure:
include: '*'
业务类:
@RestController
public class RateLimitController
{
@GetMapping("/byResource")
@SentinelResource(value = "byResource",blockHandler = "handleException")
public CommonResult byResource()
{
return new CommonResult(200,"按资源名称限流测试OK",new Payment(2020L,"serial001"));
}
public CommonResult handleException(BlockException exception)
{
return new CommonResult(444,exception.getClass().getCanonicalName()+"\t 服务不可用");
}
按资源名称限定限流+后续处理
配置:
此时关闭微服务8401,Sentienl上的控制台上流控规则消失了,说明流控规则默认是临时结点!!!
安装URL地址限流+后续处理
编码:
@GetMapping("/rateLimit/byUrl")
@SentinelResource(value = "byUrl")
public CommonResult byUrl()
{
return new CommonResult(200,"按url限流测试OK",new Payment(2020L,"serial002"));
}
配置:
测试:
兜底方法面临问题:
自定义限流处理类:
public class CustomerBlockHandler {
public static CommonResult handleException1(BlockException exception) {
return new CommonResult(4444, "按客户自定义....exception1");
}
public static CommonResult handleException2(BlockException exception) {
return new CommonResult(4444, "按客户自定义....exception2");
}
}
业务类:
@GetMapping("/rateLimit/customerBlockHandler")
@SentinelResource(value = "customerBlockHandler",
blockHandlerClass = CustomerBlockHandler.class,
blockHandler = "handlerException2")
public CommonResult customerBlockHandler()
{
return new CommonResult(200,"按客戶自定义",new Payment(2020L,"serial003"));
}
进一步说明:
好了,本篇的介绍就到此为止啦!!!