TimedCache定期缓存

TimedCache此缓存没有容量限制,对象只有在过期后才会被移除,发现2种等价用法。建议使用第一种,比较常见,第一种封装了第二种的实现.

用法一(推荐):

public static final TimedCache> timeCache = new TimedCache<>(1000);

public static void main(String[] args) throws InterruptedException {
    
    List plateNo = timeCache.get("plateNo");
    System.out.println(plateNo);
    if (Objects.isNull(plateNo)){
        time2.put("plateNo", Arrays.asList("7","8"));
    }

    System.out.println(timeCache.get("plateNo"));

    Thread.sleep(500);
    
    List plateNo2 = timeCache.get("plateNo");
    if (Objects.isNull(plateNo2)){
        time2.put("plateNo", Arrays.asList("4.5","8"));
    }
    System.out.println("timeCache:"+timeCache.get("plateNo"));

    Thread.sleep(1000);
    System.out.println("睡眠1s后");
    
    List plateNo3 = timeCache.get("plateNo");
    if (Objects.isNull(plateNo3)){
        time2.put("plateNo", Arrays.asList("45","8"));
    }

    System.out.println("time2"+timeCache.get("plateNo"));
}

用法二:

public static final Map> plateNoVillagePoint = new ConcurrentHashMap<>();
public static final TimedCache time = new TimedCache(1000, plateNoVillagePoint);

public static void main(String[] args) throws InterruptedException {
    Object o = time.get("plateNo");
    System.out.println(o);
    if (Objects.isNull(o)){
        time.put("plateNo", Arrays.asList("5","6"));
    }
    System.out.println(time.get("plateNo"));

    Thread.sleep(500);
    System.out.println("睡眠1s后");
    Object o1 = time.get("plateNo");
    if (Objects.isNull(o1)){
        time.put("plateNo", Arrays.asList("2","3"));
    }
    System.out.println("time:"+time.get("plateNo"));

    Thread.sleep(1000);
    System.out.println("睡眠1s后");
    Object o2 = time.get("plateNo");
    if (Objects.isNull(o2)){
        time.put("plateNo", Arrays.asList("1.2","3"));
    }
    System.out.println("time:"+time.get("plateNo"));
    
}

TimeCache的其他方法

	/**
	 * 构造
	 *
	 * @param timeout 超时(过期)时长,单位毫秒
	 */
	public TimedCache(long timeout) {
		this(timeout, new HashMap<>());
	}

	/**
	 * 构造
	 *
	 * @param timeout 过期时长
	 * @param map 存储缓存对象的map
	 */
	public TimedCache(long timeout, Map, CacheObj> map) {
		this.capacity = 0;
		this.timeout = timeout;
		this.cacheMap = map;
	}

	/**
	 * 清理过期对象
	 *
	 * @return 清理数
	 */
	@Override
	protected int pruneCache() {
		int count = 0;
		final Iterator> values = cacheObjIter();
		CacheObj co;
		while (values.hasNext()) {
			co = values.next();
			if (co.isExpired()) {
				values.remove();
				onRemove(co.key, co.obj);
				count++;
			}
		}
		return count;
	}

	/**
	 * 定时清理
	 *
	 * @param delay 间隔时长,单位毫秒
	 */
	public void schedulePrune(long delay) {
		this.pruneJobFuture = GlobalPruneTimer.INSTANCE.schedule(this::prune, delay);
	}

	/**
	 * 取消定时清理
	 */
	public void cancelPruneSchedule() {
		if (null != pruneJobFuture) {
			pruneJobFuture.cancel(true);
		}
	}

你可能感兴趣的:(缓存)