Java基于时间窗口的限流算法

Java基于时间窗口的限流算法

算法流程

在这里插入图片描述

CurrentLimiterInputStream

package com.liangzhm.io;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Classname CurrentLimiterInputStream
 * @Description TODO
 * @Date 2023/1/18 10:22
 * @Author liangzhm
 * @Version 1.0
 */
public class CurrentLimiterInputStream extends BufferedInputStream {

    private static int DEFAULT_BUFFER_SIZE = 8192;

    private CurrentLimiterVo streamLimitVo;

    public CurrentLimiterInputStream(InputStream inputStream, CurrentLimiterVo streamLimitVo) {
        this(inputStream, DEFAULT_BUFFER_SIZE, streamLimitVo);
    }

    public CurrentLimiterInputStream(InputStream inputStream, int size) {
        this(inputStream, size, null);
    }

    public CurrentLimiterInputStream(InputStream inputStream, int size, CurrentLimiterVo streamLimitVo) {
        super(inputStream, size);
        this.streamLimitVo = streamLimitVo;
    }

    @Override
    public int read(byte b[], int off, int len) throws IOException {
        int bytes = super.read(b, off, len);
        if (streamLimitVo != null) {
            streamLimitVo.limit(bytes);
        }
        return bytes;
    }
}

CurrentLimiterIoUtils

package com.liangzhm.io;

import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @Classname CurrentLimiterIoUtils
 * @Description TODO
 * @Date 2023/1/18 13:47
 * @Author liangzhm
 * @Version 1.0
 */
public class CurrentLimiterIoUtils {

    /**
     * @param in
     * @param out
     * @param maxRate 最大速率,单位kb,如:限速200kb/s,则maxRate填写200
     * @throws IOException
     */
    public static void copy(InputStream in, OutputStream out, int maxRate) throws IOException {
        copy(in, out, CurrentLimiterVo.of(maxRate));
    }


    /**
     * @param in
     * @param out
     * @param maxRate    最大速率,单位kb,如:限速200kb/s,则maxRate填写200
     * @param timeWindow 时间窗口,单位秒,如:限速200kb/s,则timeWindow填写1
     * @throws IOException
     */
    public static void copy(InputStream in, OutputStream out, int maxRate, int timeWindow) throws IOException {
        copy(in, out, CurrentLimiterVo.of(timeWindow, maxRate));
    }

    /**
     * @param in
     * @param out
     * @param currentLimiterVo
     * @throws IOException
     */
    public static void copy(InputStream in, OutputStream out, CurrentLimiterVo currentLimiterVo) throws IOException {
        StreamUtils.copy(new CurrentLimiterInputStream(in, currentLimiterVo), out);
    }
}

CurrentLimiterVo

package com.liangzhm.io;

import java.util.concurrent.TimeUnit;

/**
 * @Classname CurrentLimiterVo
 * @Description TODO
 * @Date 2023/1/18 12:07
 * @Author liangzhm
 * @Version 1.0
 */
public class CurrentLimiterVo {

    private static final int ONE = 1;

    private static final int KB = 1024;

    private static final int MILLION = 1000_000;

    /**
     * 纳秒
     */
    private long timeWindow;

    private int chunk;

    private long previousTime;

    private int currentBytes = 0;

    /**
     * 单位KB
     */
    private int maxRate;

    private CurrentLimiterVo(int maxRate) {
        this(ONE, maxRate);
    }

    private CurrentLimiterVo(int timeWindow, int maxRate) {
        if (timeWindow < 0) {
            throw new RuntimeException("timeWindow不合法");
        }
        if (maxRate < 0) {
            throw new RuntimeException("maxRate不合法");
        }
        this.maxRate = maxRate;
        this.timeWindow = TimeUnit.SECONDS.toNanos(timeWindow);
        this.chunk = this.maxRate * KB;
    }

    /**
     * @param maxRate
     * @return
     */
    public static CurrentLimiterVo of(int maxRate) {
        return new CurrentLimiterVo(maxRate);
    }

    /**
     * @param timeWindow
     * @param maxRate
     * @return
     */
    public static CurrentLimiterVo of(int timeWindow, int maxRate) {
        return new CurrentLimiterVo(timeWindow, maxRate);
    }

    public void limit(int bytes) {
        if (bytes <= 0) {
            return;
        }
        this.currentBytes += bytes;
        if (this.previousTime == 0) {
            this.previousTime = System.nanoTime();
        }
        while (this.currentBytes >= chunk) {
            long passTime = System.nanoTime() - this.previousTime;
            long missedTime = this.timeWindow - passTime;
            if (missedTime > 0) {
                try {
                    Thread.sleep(missedTime / MILLION, (int) (missedTime % MILLION));
                } catch (InterruptedException e) {
                }
            }
            this.currentBytes -= chunk;
            this.previousTime = System.nanoTime();
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个基于Java语言设计的简单漏桶算法限流的示例代码: ```java import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class LeakyBucket { private int capacity; // 桶的容量 private int rate; // 漏水速率 private int water; // 当前水量 private ScheduledExecutorService scheduler; // 定时任务调度器 public LeakyBucket(int capacity, int rate) { this.capacity = capacity; this.rate = rate; this.water = 0; this.scheduler = Executors.newSingleThreadScheduledExecutor(); } public void start() { scheduler.scheduleAtFixedRate(() -> { water = Math.max(0, water - rate); // 漏水操作 }, 0, 1, TimeUnit.SECONDS); // 每秒执行一次漏水操作 } public boolean allowRequest() { if (water < capacity) { water++; // 增加水量 return true; // 允许请求通过 } return false; // 水满,拒绝请求 } public void stop() { scheduler.shutdown(); // 停止漏水任务调度 } } ``` 使用示例: ```java public class Main { public static void main(String[] args) { LeakyBucket bucket = new LeakyBucket(10, 2); // 创建一个容量为10,漏水速率为2的漏桶实例 bucket.start(); // 开始漏水任务调度 for (int i = 0; i < 20; i++) { if (bucket.allowRequest()) { System.out.println("请求通过"); } else { System.out.println("请求被限流"); } try { Thread.sleep(300); // 模拟请求间隔时间 } catch (InterruptedException e) { e.printStackTrace(); } } bucket.stop(); // 停止漏水任务调度 } } ``` 在上述示例中,LeakyBucket类实现了一个简单的漏桶算法限流器。通过调整漏桶的容量和漏水速率,可以控制系统的请求流量。在主程序中,通过调用`allowRequest()`方法来判断是否允许请求通过,然后进行相应的处理。注意需要在合适的地方停止漏水任务调度,以免资源泄露。 请注意,这只是一个简单的示例代码,实际应用中可能还需要考虑线程安全性、精确性等问题,并根据具体业务需求进行适当的调整和优化。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值