# 怎么用Java寫一個簡單的緩存操作類
## 引言
在實際開發中,緩存是提高應用性能的常見手段。通過將頻繁訪問的數據存儲在內存中,可以減少對數據庫或外部服務的調用次數。本文將介紹如何用Java實現一個簡單的緩存操作類,支持基本的增刪改查功能。
---
## 一、緩存的基本概念
### 1.1 什么是緩存
緩存是一種臨時存儲數據的機制,通常用于:
- 加速數據訪問
- 減輕后端壓力
- 提升系統響應速度
### 1.2 緩存常見實現方式
- **內存緩存**:基于Java集合類(如`HashMap`)
- **分布式緩存**:如Redis、Memcached
- **本地緩存**:如Guava Cache、Caffeine
本文將聚焦于基于`ConcurrentHashMap`的線程安全內存緩存實現。
---
## 二、核心設計
### 2.1 類結構設計
```java
public class SimpleCache<K, V> {
private final Map<K, V> cacheMap;
private final long defaultExpireTime; // 默認過期時間(毫秒)
// 構造方法
public SimpleCache(long defaultExpireTime) {
this.cacheMap = new ConcurrentHashMap<>();
this.defaultExpireTime = defaultExpireTime;
}
}
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class SimpleCache<K, V> {
private final Map<K, V> cacheMap;
public SimpleCache() {
this.cacheMap = new ConcurrentHashMap<>();
}
// 添加/更新緩存
public void put(K key, V value) {
cacheMap.put(key, value);
}
// 獲取緩存
public V get(K key) {
return cacheMap.get(key);
}
// 刪除緩存
public void remove(K key) {
cacheMap.remove(key);
}
// 清空緩存
public void clear() {
cacheMap.clear();
}
// 獲取緩存大小
public int size() {
return cacheMap.size();
}
}
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
public class ExpirableCache<K, V> {
private static class CacheEntry<V> {
V value;
long expireTime;
CacheEntry(V value, long expireTime) {
this.value = value;
this.expireTime = expireTime;
}
}
private final Map<K, CacheEntry<V>> cacheMap;
private final long defaultExpireTime;
public ExpirableCache(long defaultExpireTime) {
this.cacheMap = new ConcurrentHashMap<>();
this.defaultExpireTime = defaultExpireTime;
}
public void put(K key, V value) {
put(key, value, defaultExpireTime);
}
public void put(K key, V value, long expireTime) {
long expireTimestamp = System.currentTimeMillis() + expireTime;
cacheMap.put(key, new CacheEntry<>(value, expireTimestamp));
}
public V get(K key) {
CacheEntry<V> entry = cacheMap.get(key);
if (entry == null) return null;
if (System.currentTimeMillis() > entry.expireTime) {
cacheMap.remove(key);
return null;
}
return entry.value;
}
// 其他方法同上...
}
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class SimpleCacheTest {
@Test
void testBasicOperations() {
SimpleCache<String, String> cache = new SimpleCache<>();
cache.put("key1", "value1");
assertEquals("value1", cache.get("key1"));
cache.remove("key1");
assertNull(cache.get("key1"));
}
@Test
void testExpiration() throws InterruptedException {
ExpirableCache<String, String> cache = new ExpirableCache<>(1000);
cache.put("tempKey", "tempValue");
assertEquals("tempValue", cache.get("tempKey"));
TimeUnit.MILLISECONDS.sleep(1500);
assertNull(cache.get("tempKey"));
}
}
添加定時任務清理過期數據:
private void startCleanerThread() {
new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
TimeUnit.SECONDS.sleep(60);
cacheMap.entrySet().removeIf(entry ->
System.currentTimeMillis() > entry.getValue().expireTime
);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}).start();
}
當緩存達到上限時,移除最近最少使用的數據:
import java.util.LinkedHashMap;
import java.util.Map;
public class LRUCache<K, V> extends LinkedHashMap<K, V> {
private final int maxSize;
public LRUCache(int maxSize) {
super(maxSize, 0.75f, true);
this.maxSize = maxSize;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > maxSize;
}
}
本文實現了一個具備基本功能的Java緩存類,包含: 1. 線程安全的CRUD操作 2. 過期時間管理 3. 可擴展的優化方案
實際項目中建議考慮: - 使用成熟的緩存庫(如Caffeine) - 分布式場景改用Redis - 根據業務需求調整淘汰策略
完整代碼已托管至GitHub:示例倉庫鏈接 “`
(注:實際字數約1200字,可根據需要補充更多實現細節或性能優化內容)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。