zoukankan      html  css  js  c++  java
  • dubbo如何做限流?

    public boolean isAllowable() {
    long now = System.currentTimeMillis();
    if (now > lastResetTime + interval) {
    token.set(rate);
    lastResetTime = now;
    }

    int value = token.get();
    boolean flag = false;
    while (value > 0 && !flag) {
    flag = token.compareAndSet(value, value - 1);
    value = token.get();
    }

    return flag;
    }


    token是一个AtomicInteger类型。rate表示超过一定时间以后,给你放了多次调用机会,如果这段时间token次数用完,那么只能等时间超过interval。

    对于comareAndSet的注释:
    /**
    * Atomically sets the value to the given updated value
    * if the current value {@code ==} the expected value.
    *
    * @param expect the expected value
    * @param update the new value
    * @return {@code true} if successful. False return indicates that
    * the actual value was not equal to the expected value.
    */
    public final boolean compareAndSet(int expect, int update) {
    return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }
    也就是返回true说明你更新成功了,false你的这次更新失败了,那么也就是非阻塞、非重试的方法。

    while (value > 0 && !flag 这个循环退出有两种情况:要不就是自己更新成功flag=true,要不就是别人把token用完了,导致token=0。


  • 相关阅读:
    CSS复合选择器
    CSS样式规则及字体样式
    jQuery 样式操作
    jQuery 选择器
    jQuery 的基本使用
    jQuery 介绍
    本地存储
    移动端常用开发框架
    移动端常用开发插件
    移动端click 延时解决方案
  • 原文地址:https://www.cnblogs.com/notlate/p/10228709.html
Copyright © 2011-2022 走看看