1

简单要求: - 每天、每小时或每分钟重置为 0 的命名计数器。下一个超出限制的递增请求将重置而不是递增。无需定时器/闹钟时间重置。- API 应该简单 - 线程安全

示例用法。保留用于记录或检查限制的特定应用程序/业务事件的计数器。检查特定资源的使用是否超过其每日限制并停止访问。

4

1 回答 1

2

更新:最新版本发布在 GitHub 上,供有兴趣的人使用 - https://github.com/mickyr/Awesome-Counter

到目前为止我的最小实现。如果您发现任何问题/改进领域,请提出批评。欢迎反馈,消极或积极。这将是一个学习机会:

可复位计数器类:

import java.util.concurrent.atomic.AtomicInteger;

public class ResettableCounter {
    private String policyString;
    private AtomicInteger count;

    public ResettableCounter(String name, AtomicInteger counter) {
        this.policyString = name;
        this.count = counter;
    }

    public String getPolicyString() {
        return policyString;
    }

    public void setPolicyString(String policyString) {
        this.policyString = policyString;
    }

    public AtomicInteger getCount() {
        return count;
    }

}

反策略枚举

public enum CounterPolicy{
    YEARLY("yyyy"),
    MONTHLY("yyyy/MM"),
    DAILY("yyyy/MM/dd"),
    HOURLY("yyyy/MM/dd hh"),
    PERMINUTE("yyyy/MM/dd hh:mm");

    private String format;

    private CounterPolicy(String format) {
        this.format = format;
    }

    public String getFormat(){
        return this.format;
    }
}

ResettableCounter 注册表类:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import CounterPolicy;
import ResettableCounter;

public class ResetableCounterRegistry {
    private ConcurrentHashMap<String, ResettableCounter> counterRegistry = new ConcurrentHashMap<String, ResettableCounter>();
    private CounterPolicy policy = CounterPolicy.DAILY;

    public int incrementCount(String counterName){
        ResettableCounter counter = counterRegistry.get(counterName);       
        DateFormat dateFormat = new SimpleDateFormat(policy.getFormat());
        Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        if(counter==null)counterRegistry.putIfAbsent(counterName, new ResettableCounter(dateFormat.format(cal.getTime()), new AtomicInteger()));
        counter=counterRegistry.get(counterName);
        if(!dateFormat.format(cal.getTime()).equals(counter.getPolicyString())){
            int count = counter.getCount().get();
            if(counter.getCount().compareAndSet(count, 0))
                counter.setPolicyString(dateFormat.format(cal.getTime()));
            else counter.getCount().incrementAndGet();
        }
        else counter.getCount().incrementAndGet();
        return counter.getCount().get();
    }

    public void setPolicy(CounterPolicy policy) {
        this.policy = policy;
    }   
}

正如我所说,这是最小的实现,但希望可以唤起良好的对话或帮助有类似用例的人。

于 2013-03-07T16:35:10.927 回答