日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

使用sentinel实现限流

發布時間:2025/3/19 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用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实现限流的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。