无法使用redis或其他中间件时,Java本地缓存实现




import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
 
public class SimpleLocalCache<K, V> {
    private final ConcurrentHashMap<K, CacheEntry<V>> cache = new ConcurrentHashMap<>();
 
    public V get(K key) {
        CacheEntry<V> entry = cache.get(key);
        if (entry != null && !entry.isExpired()) {
            return entry.value;
        }
        return null;
    }
 
    public void put(K key, V value, long timeout, TimeUnit timeUnit) {
        long expiryTime = (timeout > 0) ? System.currentTimeMillis() + timeUnit.toMillis(timeout) : 0;
        cache.put(key, new CacheEntry<>(value, expiryTime));
    }
 
    public void remove(K key) {
        cache.remove(key);
    }
 
    public void clear() {
        cache.clear();
    }
 
    private static class CacheEntry<V> {
        private final V value;
        private final long expiryTime;
 
        public CacheEntry(V value, long expiryTime) {
            this.value = value;
            this.expiryTime = expiryTime;
        }
 
        public boolean isExpired() {
            return expiryTime > 0 && System.currentTimeMillis() > expiryTime;
        }
    }
}
 
// 使用示例
public class CacheUsageExample {
    public static void main(String[] args) {
        SimpleLocalCache<String, String> cache = new SimpleLocalCache<>();
 
        // 存储一个键值对,有效期10秒
        cache.put("key", "value", 10, TimeUnit.SECONDS);
 
        // 获取键对应的值
        String value = cache.get("key");
        System.out.println("Value from cache: " + value);
 
        // 等待10秒后
 
        // 再次获取键对应的值
        value = cache.get("key");
        System.out.println("Value from cache after timeout: " + value); // 应该为null,因为键值对已过期
 
        // 移除键值对
        cache.remove("key");
 
        // 清空缓存
        cache.clear();
    }
}

这个简单的本地缓存实现使用了ConcurrentHashMap来存储键值对,并通过CacheEntry类来管理每个条目的过期时间。它提供了基本的缓存操作,如获取、存储、移除和清空缓存。当尝试获取已过期的条目时,会返回null。这个实现没有提供复杂的缓存策略,如LRU、LFU或者缓存空间回收,但它展示了一个基本的缓存抽象和实现。

评论已关闭

推荐阅读

Vue中使用mind-map实现在线思维导图
2024年08月04日
VUE
Web前端最全Vue实现免密登录跳转的方式_vue怎么样不登录返回首页,最强技术实现
2024年08月04日
VUE
vue3 项目搭建教程(基于create-vue,vite,Vite + Vue)
2024年08月04日
VUE
Vue-颜色选择器实现方案——>Vue-Color( 实战*1+ Demo*7)
2024年08月04日
VUE
Vue项目卡顿慢加载?这些优化技巧告诉你!_vue数据多渲染卡顿
2024年08月04日
VUE
vue中的keep-alive详解与应用场景
2024年08月04日
VUE
Vue、React实现excel导出功能(三种实现方式保姆级讲解)
2024年08月04日
vue-office/docx插件实现docx文件预览
2024年08月04日
VUE
java调用js文件的两种方法(支持V8引擎)
2024年08月04日
JavaScript:解决计算精度问题/mathjs/bignumber.js/big.js/decimal.js
2024年08月04日
两周从爬虫小白变大神 _yjs_js_security_passport
2024年08月04日
JS笔记(对象、函数、数组)
2024年08月04日
Markdown.js:强大的纯JavaScript Markdown解析器
2024年08月04日
Vue项目:js模拟点击a标签下载文件并重命名,URL文件地址下载方法、请求接口下载文件方法总结。
2024年08月04日
vue 父组件怎么获取子组件里面的data数据
2024年08月04日
VUE
个人开发实现AI套壳网站快速搭建(Vue+elementUI+SpringBoot)
2024年08月04日
el-table 表格封装并改造实现单元格可编辑
2024年08月04日
none
nodejs环境下创建vue项目、SSH密钥登陆!!!
2024年08月04日
vue+quill+element-ui实现视频、图片上传及缩放保姆级教程,轻松使用富文本
2024年08月04日
【three.js】22. Imported Models导入模型
2024年08月04日