NACOS中应用SENTINEL 熔断限流降级框架

SENTINEL 熔断限流降级框架

在学习sentinel之前我已经玩过hystrix了,看到nacos真的就感觉不需要这边引用一个框架!这边又换一个!对于初学者算友好!就是一些配置。

首先如果我们只是想,先搭建一个sentinel看看样!我导入了

			<dependency>
	            <groupId>com.alibaba.csp</groupId>
	            <artifactId>sentinel-core</artifactId>
	            <version>1.7.0</version>
	        </dependency>

然后你就可以导入

		<dependency>
	        <groupId>com.alibaba.csp</groupId>
	        <artifactId>sentinel-annotation-aspectj</artifactId>
	        <version>1.7.1</version>
	    </dependency>

来注解 @SentinelResource(value=“rule”,blockhandler=“method”) 记得写个method来降级回调。

			/**
			* 定义限流规则
			*/
			@PostConstruct
			private void initFlowRules(){
			    List<FlowRule> rules = new ArrayList<>();
			    FlowRule rule = new FlowRule();
			    rule.setResource("HelloWorld");
			    rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
			    // 设置QPS为1
			    rule.setCount(1);
			    rules.add(rule);
			    FlowRuleManager.loadRules(rules);
			}

还得定义sentinel的限流规则。之后可以在sentinel dashboard中直接鼠标操作。

参考:

    @RequestMapping("/getOrder1")
    @ResponseBody
    public String queryOrder2(@RequestParam("orderId") String orderId) {

        Entry entry = null;
        // 资源名 也就是规则名
        String resourceName = "KEY";
        try {
            // entry可以理解成入口登记
            entry = SphU.entry(resourceName);
            // 被保护的逻辑, 这里为订单查询接口
            return orderQueryService.queryOrderInfo(orderId);
        } catch (BlockException blockException) {
            // 接口被限流的时候, 会进入到这里
            LOG.warn("---getOrder1接口被限流了---, exception: ", blockException);
            return "接口限流, 返回空";
        } finally {
            // SphU.entry(xxx) 需要与 entry.exit() 成对出现,否则会导致调用链记录异常
            if (entry != null) {
                entry.exit();
            }
        }
    }

然后限流就差不多了。

补充一句,在.yml中 写入eager这个便可以启动项目在dashboard中
具体看此博客NACOS:SENTINEL DASHBOARD 的配置

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值