SentinelResource配置
一、按资源名称限流+后续处理
1、启动Nacos
2、启动Sentinel
3、在cloudalibaba-sentinel-service8401工程下的controller文件目录中新创建RateLimitController类
package com.junfu.springcloud.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.junfu.springcloud.entities.CommonResult;
import com.junfu.springcloud.entities.Payment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@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 服务不可用");
}
}
4、启动cloudalibaba-sentinel-service8401
- 在浏览器中输入http://localhost:8401/byResource测试接口
成功
5、配置流控规则
6、再次测试http://localhost:8401/byResource接口
- 正常访问(单次点击)
正常
- 快速多次访问
异常、降级处理
二、按url地址限流+后续处理
1、在RateLimitController类中新建方法byUrl()
package com.junfu.springcloud.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.junfu.springcloud.entities.CommonResult;
import com.junfu.springcloud.entities.Payment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@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 服务不可用");
}
@GetMapping("/rateLimit/byUrl")
@SentinelResource(value = "byUrl")
public CommonResult byUrl()
{
return new CommonResult(200,"按url地址限流测试OK",new Payment(2020L,"serial002"));
}
}
2、重启cloudalibaba-sentinel-service8401
- 在浏览器中输入http://localhost:8401/rateLimit/byUrl测试接口
正常
3、Sentinel控制台配置
4、再次测试http://localhost:8401/rateLimit/byUrl接口
- 正常访问(单次点击)
正常
- 快速多次访问
异常、降级处理
由于没有手动写blockHandler处理函数,因此会调用Sentinel默认处理函数
三、兜底处理函数面临的问题
1、系统默认的,没有体现我们自己的业务要求。
2、依照现有条件,我们自定义的处理方法又和业务代码耦合在一块,不直观。
3、每个业务方法都添加一个兜底的,那代码膨胀加剧。
4、全局统—的处理方法没有体现。