使用sentinel实现限流
生活随笔
收集整理的這篇文章主要介紹了
使用sentinel实现限流
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用RateLimiter可查看另外兩篇文章:
spring cloud網關(zuul)使用RateLimiter限流,使用jMeter性能測試高并發
spring cloud微服務間限流,使用jMeter性能測試高并發
導入包,pom.xml配置
<dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-annotation-aspectj</artifactId><version>1.4.1</version> </dependency>初始化限流規則,示例是在啟動類初始化,也可在其他地方編寫。
@SpringBootApplication @EnableZuulProxy public class ZuulApplication {public static void main(String[] args) {init();SpringApplication.run(ZuulApplication.class, args);}/*** 初始化限流*/private static void init(){List<FlowRule> rules = new ArrayList<>();FlowRule flowRule = new FlowRule();//資源名稱flowRule.setResource("service-order");//限流類型flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);//每秒2 QPSflowRule.setCount(2);rules.add(flowRule);FlowRuleManager.loadRules(rules);} }方案1:使用Filter
網關過濾器編寫相關邏輯?
@Component public class SentinelFilter extends ZuulFilter {@Overridepublic String filterType() {return FilterConstants.PRE_TYPE;}@Overridepublic int filterOrder() {return 0;}@Overridepublic boolean shouldFilter() {return true;}@Overridepublic Object run() throws ZuulException {Entry entry = null;try{entry = SphU.entry("service-order");//業務邏輯System.out.println("正常請求");}catch (Exception e){System.out.println("限流了");}finally {if(entry != null){entry.exit();}}return null;} }注意Entry選擇:阿里巴巴包下:com.alibaba.csp.sentinel.Entry
?
方案2:使用注解
新增服務類:
@Service public class SentinelService {/*** 正常請求* @return*/@SentinelResource(value = "service-order",blockHandler = "fail")public String success(){System.out.println("正常請求!");return "success";}/*** 阻塞* @return*/public String fail(BlockException e){System.out.println("被限流了");return "fail";} }編寫controller測試類:
@RestController @RequestMapping("/limit") public class LimitTestController {@Autowiredprivate SentinelService sentinelService;@RequestMapping("/limitTest")public String limitTest(){// return "1111111";return sentinelService.success();} }在啟動類增加注入bean:
@Beanpublic SentinelResourceAspect sentinelResourceAspect(){return new SentinelResourceAspect();}初始化限流規則與方案1一致。
?
總結
以上是生活随笔為你收集整理的使用sentinel实现限流的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring cloud微服务间限流,使
- 下一篇: rocketmq基本安装与使用(一)