zno2

java map缓存数据自动过期

 

package ztest;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 页面跳转时产生一个 token
 * 带到页面
 * 页面保存时校验token
 * 
 * 防止重复提交
 * 
 * */
public final class TokenCache {
    
    private static final Map<String, WrapMapValue> CACHE = new HashMap<String, WrapMapValue>();
    private static final int DELAY_TIME_IN_MILLIS = 0;
    private static final int PERIOD_TIME_IN_MILLIS = 5 * 60 * 1000;

    static {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Iterator<WrapMapValue> it = CACHE.values().iterator();
                while (it.hasNext()) {
                    WrapMapValue _v = it.next();
                    if (_v.getCreateTimeInMillis() + _v.getExpirytimeInMillis() < new Date().getTime()) {
                        it.remove();
                    }
                }
            }
        }, DELAY_TIME_IN_MILLIS, PERIOD_TIME_IN_MILLIS);
    }
    
    private TokenCache(){
        
    }

    public static void put(String key, String value, long expiryTimeInMillis) {
        CACHE.put(key, new WrapMapValue(new Date().getTime(), expiryTimeInMillis, value));
    }

    public static String get(String key) {
        WrapMapValue _v = CACHE.get(key);
        if (_v.getCreateTimeInMillis() + _v.getExpirytimeInMillis() >= new Date().getTime()) {
            return _v.getMapValue();
        } else {
            return null;
        }
    }

}

class WrapMapValue {
    private long bornTimeInMillis;
    private long lifeTimeInMillis;
    private String mapValue;

    WrapMapValue(long bornTimeInMillis, long lifeTimeInMillis, String mapValue) {
        this.bornTimeInMillis = bornTimeInMillis;
        this.lifeTimeInMillis = lifeTimeInMillis;
        this.mapValue = mapValue;
    }

    public long getCreateTimeInMillis() {
        return bornTimeInMillis;
    }

    public long getExpirytimeInMillis() {
        return lifeTimeInMillis;
    }

    public String getMapValue() {
        return mapValue;
    }
}

 

posted on 2023-06-01 16:53  zno2  阅读(519)  评论(0编辑  收藏  举报

导航