Strategie di caching

Ottimizzazione del codice in Java

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

Cos’è il caching?

Il caching è come tenere gli ingredienti usati spesso sul bancone invece che in dispensa: li prendi più in fretta, ma lo spazio è limitato

In genere facciamo cache di:

  • Risultati di query al database
  • Risposte di API
  • Calcoli costosi
  • Altre operazioni pesanti
Ottimizzazione del codice in Java

Caching in memoria in 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);
    }
}
Ottimizzazione del codice in Java

Policy di eviction della cache

  • LRU (Least Recently Used)
  • LFU (Least Frequently Used)
  • FIFO (First In, First Out)
  • Scadenza a tempo
  • E altro!
Ottimizzazione del codice in Java

Redis per il caching distribuito

Cos’è Redis:

  • Data store/cache in memoria
  • Ottimo come cache distribuita
  • Supporta molte strutture dati
  • Molti client Java: ad es. Jedis

Schermata 2025-05-14 alle 18.59.29.png

Ottimizzazione del codice in Java

Usare Redis con Jedis

import redis.clients.jedis.Jedis;

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

Funzionalità aggiuntive:

  • Scadenza automatica degli elementi in cache
  • Supporto cluster
Ottimizzazione del codice in Java

Implementare un cache a tempo con 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);
    }
}
Ottimizzazione del codice in Java

Riepilogo

  • Il caching salva risultati per evitare ricalcoli
  • Utile per operazioni costose e dati spesso richiesti
  • Imposta politiche di eviction per gestire la memoria
  • Valuta il caching distribuito per app multi-server (es. Redis con Jedis)
Ottimizzazione del codice in Java

Ayo berlatih!

Ottimizzazione del codice in Java

Preparing Video For Download...