欢迎访问我的个人网站==》 jiashubing.cn

Java限制某段时间内某个请求的次数(代码库)

关键就是统计次数

技巧:
1、使用guava cache缓存 来计数
2、利用引用变量的特性,减少put,只使用get

如果重新put赋值,缓存的时间会刷新,比如下面例子的b,一共输出了7次,而a只输出了5次

import com.google.common.cache.Cache;

public class Test2 {
    private static Cache<String, TestObj> guavaCache = CacheFactory.cached(5L, null);
    public static void main(String[] args) {
        guavaCache.put("a", new TestObj());
        guavaCache.put("b", new TestObj());
        for (int i = 0; i < 10; i++) {
            TestObj a = guavaCache.getIfPresent("a");
            if (a == null) {
                System.out.println("a == null");
            } else {
                a.setNum(a.getNum() + 1);
                System.out.println("a == " + a.getNum());
            }

            TestObj b = guavaCache.getIfPresent("b");
            if (b == null) {
                System.out.println("b == null");
            } else {
                b.setNum(b.getNum() + 1);
                System.out.println("b == " + b.getNum());
            }

            if (i == 2) {
                TestObj tmp = new TestObj();
                tmp.setNum(1000);
                guavaCache.put("b", tmp);
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

 

public class TestObj {
    private int num = 0;

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }
}

 

输出内容如下:

a == 1
b == 1
a == 2
b == 2
a == 3
b == 3
a == 4
b == 1001
a == 5
b == 1002
a == null
b == 1003
a == null
b == 1004
a == null
b == null
a == null
b == null
a == null
b == null

 

原创文章,欢迎转载,转载请注明出处!

posted @ 2023-08-24 17:03  贾树丙  阅读(41)  评论(0编辑  收藏  举报