import java.util.concurrent.ConcurrentHashMap;
public class LocalCacheExample {
// 使用 ConcurrentHashMap 作为本地缓存
private static final ConcurrentHashMap<String, String> cache = new ConcurrentHashMap<>();
/**
* 获取缓存中的值
* @param key 键
* @return 缓存中的值,如果不存在则返回 null
*/
public static String getFromCache(String key) {
return cache.get(key);
}
/**
* 将键值对放入缓存中
* @param key 键
* @param value 值
*/
public static void putToCache(String key, String value) {
cache.put(key, value);
}
/**
* 移除缓存中的键值对
* @param key 键
*/
public static void removeFromCache(String key) {
cache.remove(key);
}
public static void main(String[] args) {
// 示例:使用本地缓存
String key = "exampleKey";
String value = "exampleValue";
// 放入缓存
putToCache(key, value);
// 从缓存中获取值
String cachedValue = getFromCache(key);
System.out.println("Cached Value: " + cachedValue); // 输出: Cached Value: exampleValue
// 移除缓存中的键值对
removeFromCache(key);
System.out.println("After removal: " + getFromCache(key)); // 输出: After removal: null
}
}
null
。这个简单的例子展示了如何在 Java 中实现一个基本的本地缓存机制。
上一篇:java object转对象
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站