# Java 带过期的 Map

📆 2021-12-16 19:12

# 实现

public class SimpleExpireMap {
    private final Map<String,Object> dataMap = new HashMap<>();// 数据map
    private final Map<String,Long> timeMap = new HashMap<>();// 时间map

    public synchronized void put(String key,Object value,long expiryAt){
        dataMap.put(key,value);
        timeMap.put(key,expiryAt);
    }

    public synchronized void remove(String key){
        dataMap.remove(key);
        timeMap.remove(key);
    }

    public synchronized Object get(String key){
        if(_isExpire(key)){
            remove(key);
            return null;
        }else{
            return dataMap.get(key);
        }
    }

    public synchronized void clear(){
        Set<String> keys=timeMap.keySet();
        Set<String> toRemoveKeys=new HashSet<>(keys.size());
        for (String k : keys) {
            if(_isTimeExpire(timeMap.get(k))) {
                toRemoveKeys.add(k);
            }
        }
        for (String k : toRemoveKeys) {
            remove(k);
        }
    }

    private boolean _isExpire(String key){
        Long time=timeMap.get(key);
        if(time==null){
            return false;
        }else{
            return _isTimeExpire(time);
        }
    }

    private boolean _isTimeExpire(long time){
        return time <= System.currentTimeMillis();
    }

}

# 使用

private final SimpleExpireMap expireMap=new SimpleExpireMap();

public String sendPhoneVerifyCode(String phone) {
    String oldCode=(String)expireMap.get(phone);
    if(oldCode!=null) return -1;

    String code=String.valueOf(new Random().nextInt(8999)+1000);

    expireMap.put(phone, code, System.currentTimeMillis()+60_000L);

    expireMap.clear();

    return code;
}
最后更新于: 12/18/2021, 8:28:10 PM