如何使用:官网:https://github.com/alibaba/Sentinel/wiki/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8
1. 按照资源名称限流:
在原先的模块8401中增加 RateLimitcontroller:
package com.fan.springcloud.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RateLimitcontroller {
//按照资源名称限流
@GetMapping("/byResource")
@SentinelResource(value = "byResource" ,
blockHandler = "handlerException")
public String byResource(){
return "code:200,message:按照资源名称限流测试";
}
//兜底的方法
public String handlerException(BlockException exception){
return "code:4444,message:"+exception.getClass().getCanonicalName()+
"\t 服务不可用";
}
}
配置项:
快速点击出现:
2. 按照Url地址限流:
RateLimitcontroller增加以下内容:
//按照Url地址限流
@GetMapping("/rateLimit/byUrl")
@SentinelResource(value = "byUrl")
public String byUrl(){
return "code:200,message:按照Url地址限流测试ok";
}
sentinel控制台配置:
快速点击出现以下限流:
3. 上面兜底方案面临的问题:
4. 客户自定义限流:
(1)RateLimitcontroller增加如下内容:
//客户自定义限流
@GetMapping("/rateLimit/customerBlockHandler")
@SentinelResource(value = "customerBlockHandler")
public String customerBlockHandler(){
return "code:200,message:按照客户自定义限流测试ok";
}
(2)自定义限流处理类:myhandler.CustomerBlockHandler:
package com.fan.springcloud.myhandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
public class CustomerBlockHandler {
public static String handlerException(BlockException exception){
return "code:4444,message:按照客户自定义,全局的handlerException---111";
}
public static String handlerException2(BlockException exception){
return "code:4444,message:按照客户自定义,全局的handlerException---222";
}
}
完善RateLimitcontroller:
//客户自定义限流
@GetMapping("/rateLimit/customerBlockHandler")
@SentinelResource(value = "customerBlockHandler",
blockHandlerClass = CustomerBlockHandler.class,
blockHandler = "handlerException2")
public String customerBlockHandler(){
return "code:200,message:按照客户自定义限流测试ok";
}
测试1:http://localhost:8401/rateLimit/customerBlockHandler
sentinel控制台配置:
测试2: http://localhost:8401/rateLimit/customerBlockHandler
总结说明:
5. 更多注解属性说明:
如何使用:官网:https://github.com/alibaba/Sentinel/wiki/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8