PHP 애플리케이션에서 캐시를 적용하지 않으면 성능 저하와 불필요한 리소스 낭비가 발생합니다. 다음은 캐시 미적용으로 인한 문제들과 간단한 해결책들입니다.
문제: 동일한 데이터를 반복적으로 생성하여 성능 저하
해결책:
function getCachedData($key, $callback, $ttl = 3600) {
$cacheFile = "/tmp/cache_{$key}.json";
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $ttl) {
return json_decode(file_get_contents($cacheFile), true);
}
$data = $callback();
file_put_contents($cacheFile, json_encode($data));
return $data;
}
// 사용 예시
$data = getCachedData('user_list', function() {
return fetchUsersFromDatabase();
});
문제: 서버 리소스를 과도하게 사용하는 반복 연산
해결책:
function getMemoryCache($key, $callback, $ttl = 3600) {
if (apcu_exists($key)) {
return apcu_fetch($key);
}
$data = $callback();
apcu_store($key, $data, $ttl);
return $data;
}
// 사용 예시
$result = getMemoryCache('expensive_calculation', function() {
return performHeavyCalculation();
});
문제: PHP 코드가 매번 컴파일되어 성능 저하
해결책:
; php.ini 설정
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.validate_timestamps=1
문제: 동일한 쿼리를 반복 실행하여 DB 부하 증가
해결책:
class QueryCache {
private $cache = [];
public function query($sql, $params = []) {
$key = md5($sql . serialize($params));
if (isset($this->cache[$key])) {
return $this->cache[$key];
}
$result = $this->executeQuery($sql, $params);
$this->cache[$key] = $result;
return $result;
}
}
문제: 정적 리소스가 매번 다운로드되어 페이지 로딩 느림
해결책:
// 이미지, CSS, JS 등 정적 파일에 대한 캐시 헤더
if (preg_match('/\.(css|js|png|jpg|gif)$/', $_SERVER['REQUEST_URI'])) {
header('Cache-Control: public, max-age=86400'); // 1일
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 86400) . ' GMT');
}
// API 응답 캐싱
header('Cache-Control: public, max-age=300'); // 5분
header('ETag: ' . md5($responseData));
문제: 세션 데이터를 매번 재계산하여 성능 저하
해결책:
function getCachedSession($key, $callback) {
if (isset($_SESSION["cache_{$key}"])) {
return $_SESSION["cache_{$key}"];
}
$data = $callback();
$_SESSION["cache_{$key}"] = $data;
return $data;
}
// 사용 예시
$userPermissions = getCachedSession('permissions', function() {
return loadUserPermissions($_SESSION['user_id']);
});
문제: 동일한 템플릿을 매번 렌더링하여 CPU 낭비
해결책:
function renderTemplate($template, $data, $cache = true) {
$cacheKey = md5($template . serialize($data));
$cacheFile = "/tmp/template_{$cacheKey}.html";
if ($cache && file_exists($cacheFile) && filemtime($cacheFile) > (time() - 3600)) {
return file_get_contents($cacheFile);
}
$output = processTemplate($template, $data);
if ($cache) {
file_put_contents($cacheFile, $output);
}
return $output;
}