快取策略

Java 程式碼最佳化

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

什麼是快取?

快取就像把常用食材放在流理台而不是櫥櫃上——取用更快,但台面空間有限

常見會快取:

  • 資料庫查詢結果
  • API 回應
  • 高成本計算
  • 其他資源密集的操作
Java 程式碼最佳化

Java 的記憶體內快取

// In-memory cache using HashMap
public class SimpleCache<K, V> {
    private final Map<K, V> cache = new HashMap<>();

    public V get(K key) {
        return cache.get(key);
    }

    public void put(K key, V value) {
        cache.put(key, value);
    }
}
Java 程式碼最佳化

快取淘汰策略

  • LRU(Least Recently Used,最近最少使用)
  • LFU(Least Frequently Used,最少次數使用)
  • FIFO(First In, First Out,先進先出)
  • 依時間到期
  • 以及其他!
Java 程式碼最佳化

分散式快取的 Redis

Redis 是什麼:

  • 記憶體內資料存放/快取
  • 擅長分散式快取
  • 支援多種資料結構
  • 有許多 Java 用戶端函式庫,例如 Jedis

Screenshot 2025-05-14 at 6.59.29 PM.png

Java 程式碼最佳化

搭配 Jedis 使用 Redis

import redis.clients.jedis.Jedis;

// Using Jedis client
Jedis jedis = new Jedis("localhost");
jedis.set("key", "value");
String value = jedis.get("key");

其他功能:

  • 快取項目自動到期
  • 支援叢集
Java 程式碼最佳化

用 Redis 實作時間型快取

public class RedisTimedCache {
    private final Jedis jedis;

    public RedisTimedCache(String host, int port) {
        this.jedis = new Jedis(host, port);
    }

    public String get(String key) {
        return jedis.get(key);
    }

    public void put(String key, String value, int timeToLiveSeconds) {
        // Sets both the value and expiration time in seconds
        jedis.setex(key, timeToLiveSeconds, value);
    }
}
Java 程式碼最佳化

重點整理

  • 快取將計算結果保存起來,避免重算
  • 適用於高成本操作與高頻存取的資料
  • 實作合適的淘汰策略以管理記憶體
  • 多伺服器應用可考慮分散式快取(例如 Redis 搭配 Jedis)
Java 程式碼最佳化

一起來練習吧!

Java 程式碼最佳化

Preparing Video For Download...