【sentinel】漏桶算法在Sentinel中的应用

这篇具有很好参考价值的文章主要介绍了【sentinel】漏桶算法在Sentinel中的应用。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

漏桶算法

漏桶算法介绍

漏桶算法,又称leaky bucket。
【sentinel】漏桶算法在Sentinel中的应用
从图中我们可以看到,整个算法其实十分简单。首先,我们有一个固定容量的桶,有水流进来,也有水流出去。对于流进来的水来说,我们无法预计一共有多少水会流进来,也无法预计水流的速度。但是对于流出去的水来说,这个桶可以固定水流出的速率。而且,当桶满了之后,多余的水将会溢出。

我们将算法中的水换成实际应用中的请求,我们可以看到漏桶算法天生就限制了请求的速度。当使用了漏桶算法,我们可以保证接口会以一个常速速率来处理请求。所以漏桶算法天生不会出现临界问题。

漏桶算法的实现

漏桶算法具体的实现代码如下:

package com.morris.user.demo;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 漏桶算法
 */
@Slf4j
public class LeakyBucketDemo {

    public static void main(String[] args) {
        LeakyBucket sideWindow = new LeakyBucket(2);
        for (int i = 0; i < 30; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(new Random().nextInt(30000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info(finalI + "--> " + sideWindow.canPass());
            }).start();
        }
    }

    public static class LeakyBucket {

        // 桶的容量
        private static final long CAPACITY = 10;
        // 水漏出的速度(每秒系统能处理的请求数)
        private final long rate;
        // 当前水量(当前累积请求数)
        private double water = 0;
        // 上一次请求的时间
        private long lastRequestTime = System.currentTimeMillis();

        /**
         * @param maxCount 1秒内允许的最大请求数
         */
        public LeakyBucket(int maxCount) {
            // 每秒允许的最大请求数
            this.rate = maxCount;
        }

        public synchronized boolean canPass() {
            long now = System.currentTimeMillis();

            // 去除从lastRequestTime~now时间段应该从桶中漏出的水
            this.water = Math.max(0, water - (now - lastRequestTime) * 1.0D / 1000 * this.rate);

            this.lastRequestTime = now;

            if (this.water + 1 > CAPACITY) {
                // 桶满了
                return false;
            }
            this.water++;
            return true;
        }

    }
}

漏桶算法的实现2

漏桶算法的另一种具体实现代码如下:

package com.morris.user.demo;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 漏桶算法
 */
@Slf4j
public class LeakyBucketDemo2 {

    public static void main(String[] args) {
        LeakyBucket sideWindow = new LeakyBucket(2);
        for (int i = 0; i < 30; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(new Random().nextInt(3000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info(finalI + "--> " + sideWindow.canPass());
            }).start();
        }
    }

    public static class LeakyBucket {

        // 上一次请求的时间
        private long lastRequestTime = System.currentTimeMillis();
        // 两次请求之间的最小时间间隔
        private final int interval;

        public LeakyBucket(int maxCount) {
            this.interval = 1000 / maxCount;
        }

        public synchronized boolean canPass() {
            long now = System.currentTimeMillis();
            // 两次请求之间的时间间隔
            if (now - lastRequestTime >= interval) {
                lastRequestTime = now;
                return true;
            }
            return false;
        }

    }
}

漏桶算法的优缺点

优点:

  • 可以平滑限制请求的处理速度,避免瞬间请求过多导致系统崩溃或者雪崩。
  • 可以控制请求的处理速度,使得系统可以适应不同的流量需求,避免过载或者过度闲置。
  • 可以通过调整桶的大小和漏出速率来满足不同的限流需求,可以灵活地适应不同的场景。

缺点:

  • 需要对请求进行缓存,会增加服务器的内存消耗。
  • 对于流量波动比较大的场景,需要较为灵活的参数配置才能达到较好的效果。
  • 但是面对突发流量的时候,漏桶算法还是循规蹈矩地处理请求,这不是我们想看到的啦。流量变突发时,我们肯定希望系统尽量快点处理请求,提升用户体验嘛。

漏桶算法的缺点主要是由于服务和漏下来的请求之间没有交互,要么服务太忙,要么服务太闲,这就引出了令牌桶算法。

漏桶算法在sentinel中的应用

漏桶算法主要用于流控规则中流控效果为排队等待。

com.alibaba.csp.sentinel.slots.block.flow.controller.RateLimiterController#canPass(com.alibaba.csp.sentinel.node.Node, int, boolean)文章来源地址https://www.toymoban.com/news/detail-471123.html

public boolean canPass(Node node, int acquireCount, boolean prioritized) {
    // Pass when acquire count is less or equal than 0.
    if (acquireCount <= 0) {
        return true;
    }
    // Reject when count is less or equal than 0.
    // Otherwise,the costTime will be max of long and waitTime will overflow in some cases.
    if (count <= 0) {
        return false;
    }

    // 当前时间
    long currentTime = TimeUtil.currentTimeMillis();

    // 计算两个请求中间允许的时间间隔
    // Calculate the interval between every two requests.
    long costTime = Math.round(1.0 * (acquireCount) / count * 1000);

    // Expected pass time of this request.
    // 下一次请求期待的访问时间
    long expectedTime = costTime + latestPassedTime.get();

    if (expectedTime <= currentTime) {
        // 当前时间大于下一次请求期待的访问时间,允许通过
        // Contention may exist here, but it's okay.
        latestPassedTime.set(currentTime);
        return true;
    } else {
        // Calculate the time to wait.
        // 计算当前线程需要等待的时间
        long waitTime = costTime + latestPassedTime.get() - TimeUtil.currentTimeMillis();
        if (waitTime > maxQueueingTimeMs) {
            // 等待时间大于设置的最大的等待超时时间
            return false;
        } else {
            // latestPassedTime+costTime就是下一次请求期待的访问时间
            long oldTime = latestPassedTime.addAndGet(costTime);
            try {
                waitTime = oldTime - TimeUtil.currentTimeMillis();
                if (waitTime > maxQueueingTimeMs) {
                    // 说明latestPassedTime被另一个线程改了
                    // 把时间改回去,然后请求不允许通过
                    latestPassedTime.addAndGet(-costTime);
                    return false;
                }
                // in race condition waitTime may <= 0
                if (waitTime > 0) {
                    // 线程休眠,排队等待
                    Thread.sleep(waitTime);
                }
                return true;
            } catch (InterruptedException e) {
            }
        }
    }
    return false;
}

到了这里,关于【sentinel】漏桶算法在Sentinel中的应用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Sentinel dashboard无法查询到应用的限流配置问题以及解决

    使用sentinle-dashboard控制台 项目整体升级后,发现控制台上无法看到流控规则了 之前的问题是无法注册上来 现在是注册上来了。结果看不到流控规则配置了。 关于注册不上来的问题,可以看另一篇文章 https://blog.csdn.net/a15835774652/article/details/132234943 项目的组件版本如下 sprin

    2024年02月11日
    浏览(34)
  • redis集群和分片-Redis Cluster:分布式环境中的数据分片、主从复制和 Sentinel 哨兵

    当涉及到 Redis 中的集群、分片、主从复制和 Sentinel 哨兵时,这些是构建分布式 Redis 环境中非常重要的概念和组件。下面详细介绍这些概念以及它们在分布式环境中的作用。 Redis Cluster 是 Redis 官方提供的分布式解决方案,用于管理和维护多个 Redis 节点的分布式数据存储。R

    2024年02月13日
    浏览(40)
  • SpringCloud Alibaba Sentinel 与 SpringCloud Gateway 的限流有什么差别?(三种限流算法原理分析)

    目录 一、Sentinel 与 Gateway 的限流有什么差别? 1.1、前置知识 - 四种常见的限流算法 1.1.1、Tips 1.1.2、计数器算法 1)固定窗口计数器算法 2)滑动窗口计数器算法 1.1.3、令牌桶算法 1.1.4、漏桶算法 1.2、解决问题 1.1.1、Tips 限流, 就是指对服务器请求量做限制,避免因为突发的

    2024年01月25日
    浏览(43)
  • 深入理解Sentinel系列-1.初识Sentinel

    👏作者简介:大家好,我是爱吃芝士的土豆倪,24届校招生Java选手,很高兴认识大家 📕系列专栏:Spring源码、JUC源码、Kafka原理、分布式技术原理 🔥如果感觉博主的文章还不错的话,请👍三连支持👍一下博主哦 🍂博主正在努力完成2023计划中:源码溯源,一探究竟 📝联

    2024年02月04日
    浏览(32)
  • 初始Sentinel(Sentinel的简单介绍及项目整合)

    前言:大家好,我是小威,24届毕业生,在一家满意的公司实习。本篇文章将详细介绍Sentinel的概念,优点,与Hystrix的对比以及微服务中整合Sentinel,后续文章将详细介绍Sentinel的细节部分。 如果文章有什么需要改进的地方还请大佬不吝赐教 👏👏。 小威在此先感谢各位大佬

    2024年02月05日
    浏览(32)
  • Sentinel dashboard的使用;Nacos保存Sentinel限流规则

    Nacos环境搭建 Nacos注册中心的使用 Nacos配置中心的使用 Sentinel 容灾中心的使用 Sentinel · alibaba/spring-cloud-alibaba Wiki · GitHub github地址:Sentinel/sentinel-dashboard at master · alibaba/Sentinel · GitHub 创建sentinel-dashboard的启动脚本,并添加如下信息: 目录: 注意:sentinel-dashboard默认会在87

    2024年02月15日
    浏览(33)
  • Spring Cloud Gateway集成Sentinel 1.8.6及Sentinel Dashboard

    一、安装sentinel 1.下载地址:sentinel v1.8.6 2.启动sentinel dashboard,执行以下命令: java -Dcsp.sentinel.log.dir=D:xxxsentinellogs -Dserver.port=9217 -Dcsp.sentinel.dashboard.server=localhost:9217 -Dcsp.sentinel.heartbeat.client.ip=localhost -Dproject.name=sentinel-dashboard -Dsentinel.dashboard.auth.username=sentinel -Dsentinel.dashboar

    2024年02月11日
    浏览(43)
  • SpringCloud Alibaba - Sentinel 高级玩法,修改 Sentinel-dashboard 源码,实现 push 模式

    目录 一、规则持久化 1.1、什么是规则持久化 1.1.1、使用背景 1.1.2、规则管理的三种模式 a)原始模式 b)pull 模式 c)push 模式 1.2、实现 push 模式 1.2.1、修改 order-service 服务,使其监听 Nacos 配置中心 1.2.2、修改 Sentinel-dashboard 源码,配置 nacos 数据源 1.2.3、修改 Sentinel-dashboard

    2024年02月07日
    浏览(35)
  • 如何使用Sentinel做流量控制?此文将附代码详细介绍Sentinel几种限流模式

    前言:大家好,我是小威,24届毕业生,在一家满意的公司实习。本篇文章将详细介绍Sentinel的两种限流模式,由于篇幅原因,后续文章将详细介绍Sentinel的其他三种。 如果文章有什么需要改进的地方还请大佬不吝赐教 👏👏。 小威在此先感谢各位大佬啦~~🤞🤞 🏠个人主页

    2024年02月05日
    浏览(31)
  • 限流:计数器、漏桶、令牌桶 三大算法的原理与实战(史上最全)

    限流是面试中的常见的面试题(尤其是大厂面试、高P面试) 注:本文以 PDF 持续更新,最新尼恩 架构笔记、面试题 的PDF文件,请到文末《技术自由圈》公号获取 为什么要限流 简单来说: 限流在很多场景中用来限制并发和请求量,比如说秒杀抢购,保护自身系统和下游系统

    2023年04月17日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包