sentinal 限流详解

1.使用sentinal 对资源(一个java方法或者http接口)进行限流,下面代码每一秒2个请求,但是经过sentinal的qps限流设置1,所以一半请求进来,一半被拦截了。

public class Test1 {

    public static void main(String[] args) throws InterruptedException {
        // 限流 规则
        List<FlowRule> rules = new ArrayList<FlowRule>();
        FlowRule rule = new FlowRule();
        // 设置 资源名称
        rule.setResource("http://localhost:8080/Test1");
        // 设置限流规则为QPS
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // QPS限制, 每秒不能超过一个请求
        rule.setCount(1);
        // 指定应用名称
        // rule.setLimitApp("test1");
        rules.add(rule);
        // 导入限流规则
        FlowRuleManager.loadRules(rules);
        while (true) {
            Entry entry = null;
            try {
                // 检查 资源是否 被sentinel触发保护机制了,会抛出异常
                entry = SphU.entry("http://localhost:8080/Test1");
                System.err.println("正常运行接口>>" + new SimpleDateFormat("hh:mm:ss").format(new Date()));
            } catch (BlockException e) {
                System.err.println("被限流了==========================");
            } finally {
                if (entry != null) {
                    // 退出限流
                    entry.exit();
                }
            }
            Thread.sleep(500);
        }
    }
}

在这里插入图片描述
maven

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

2.整合dubbo,对dubbo接口进行限流
maven配置

<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-alibaba-sentinel</artifactId>
			<version>0.9.0.RELEASE</version>
		</dependency>
		<!-- dubbo整合适配器 -->
		<dependency>
			<groupId>com.alibaba.csp</groupId>
			<artifactId>sentinel-apache-dubbo-adapter</artifactId>
			<version>1.6.3</version>
		</dependency>
		<dependency>
		<!-- 后台管理控制交互 -->
		<groupId>com.alibaba.csp</groupId>
			<artifactId>sentinel-transport-simple-http</artifactId>
			<version>1.6.3</version>
		</dependency>

在dubbo接口上加一个注解
在这里插入图片描述
启动dubbo服务时加上jvm参数(指定dashboard控制台地址)
Dcsp.sentinel.dashboard.server=localhost:8080

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值