栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java漏洞桶简单实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java漏洞桶简单实现

Java漏洞桶代码:


import lombok.Getter;


@Getter
public class Funnel {

    
    private int capacity;
    
    private double leakingRate;
    
    private int leftQuota;
    
    private long leakingTs;

    public Funnel(int capacity, double leakingRate, int leftQuota, long leakingTs) {
        this.capacity = capacity;
        this.leakingRate = leakingRate;
        this.leftQuota = leftQuota;
        this.leakingTs = leakingTs;
    }

    
    public Boolean water(int quota) {
        makeSpace();
        // 表示量充足
        if (leftQuota >= quota) {
            leftQuota = leftQuota - quota;
            return true;
        }
        // 剩余量不够
        return false;
    }

    
    private void makeSpace() {
        long nowTs = System.currentTimeMillis();
        // 这个是间隔的时间
        long deltaTs = nowTs - this.leakingTs;
        // 漏掉的水
        int deltaQuota = (int) (deltaTs * leakingRate);
        // 间隔时间太长,溢出
        if (deltaQuota < 0) {
            this.leftQuota = capacity;
            this.leakingTs = nowTs;
            return;
        }
        // 说明漏的时间不够
        if (deltaQuota < 1) {
            return;
        }
        this.leakingTs = nowTs;
        this.leftQuota = this.leftQuota + deltaQuota;
        if (this.leftQuota > this.capacity) {
            this.leftQuota = this.capacity;
        }
    }

}

测试代码:

public class FunnelLimitRate {
    private static Map funnels = new HashMap<>();


    public static void main(String[] args) throws InterruptedException {
        String userId = "2019";
        String actionKey = "rgister";
        int capacity = 8;
        double leakingRate = 0.001;
        int leftQuota = 5;
        Funnel funnel = funnels.get(userId);
        if (funnel == null) {
            funnel = new Funnel(capacity, leakingRate, leftQuota, System.currentTimeMillis());
        }
        // 每1000ms(1s),流入1的水
        // 每1000ms,流出1000*leakingRate(而且要>1)的水
        for (int i = 0; i < 8; i++) {
            Boolean isBoolean = funnel.water(1);
            TimeUnit.MILLISECONDS.sleep(1000);
            System.out.println(isBoolean + " " + funnel.getLeakingRate());
        }

    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/874145.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号