package com.testor.module.video.util;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.util.concurrent.TimeUnit;
import java.util.function.Function;

public class CacheUtil {
	private static Cache<String, String> cache;

	static {
		cache = createCache();
	}

	/**
	 * 存储K-V
	 *
	 * @param key
	 * @param value
	 * @return
	 */
	public static String put(String key, String value) {
		cache.put(key, value);
		return key;
	}

	/**
	 * 获取K-V
	 *
	 * @param key
	 * @return
	 */
	public static String getIfPresent(String key) {
		return cache.getIfPresent(key);
	}

	public static String get(String key, Function<String, String> function) {
		return cache.get(key, function);
	}

	public static void remove(String key) {
		cache.invalidate(key);
	}

	private static class CacheSingletonHolder {
		private final static Cache<String, String> CACHE = Caffeine.newBuilder()
			// 初始的缓存空间大小
			.initialCapacity(100)
			// 缓存的最大条数
			.maximumSize(1000)
			// 最后一次缓存访问过后,15分钟后失效
			.expireAfterAccess(15, TimeUnit.MINUTES)
			.build();
	}
	private static Cache<String, String> createCache() {
		return CacheSingletonHolder.CACHE;
	}

}
