การปรับแต่งโค้ดใน Java
Pavlos Kosmetatos
Lead Engineer @Wealthyhood
การแคชคือการเก็บข้อมูลที่ใช้บ่อยไว้ในตำแหน่งที่เข้าถึงได้เร็ว แต่มีพื้นที่จำกัด
ข้อมูลที่มักแคชไว้:
// 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);
}
}
Redis คืออะไร:

import redis.clients.jedis.Jedis;
// Using Jedis client
Jedis jedis = new Jedis("localhost");
jedis.set("key", "value");
String value = jedis.get("key");
ฟีเจอร์เพิ่มเติม:
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