文件缓存:带过期与原子写入
把计算结果缓存成文件,先写临时文件再 rename,避免读到写了一半的内容;支持过期与删除。
更新于 2026-11-0156 行代码
完整代码
PHP
<?php
class FileCache
{
private string $dir;
public function __construct(string $dir)
{
$this->dir = rtrim($dir, '/');
if (!is_dir($this->dir)) {
@mkdir($this->dir, 0755, true);
}
}
private function path(string $key): string
{
return $this->dir . '/' . sha1($key) . '.cache';
}
public function get(string $key, $default = null)
{
$file = $this->path($key);
if (!is_file($file)) {
return $default;
}
$raw = @file_get_contents($file);
if ($raw === false) {
return $default;
}
$pos = strpos($raw, "\n");
if ($pos === false) {
return $default;
}
if ((int)substr($raw, 0, $pos) < time()) {
@unlink($file);
return $default;
}
$val = @unserialize(substr($raw, $pos + 1), ['allowed_classes' => false]);
return $val === false ? $default : $val;
}
public function set(string $key, $value, int $ttl = 300): bool
{
$file = $this->path($key);
$tmp = $file . '.' . getmypid() . '.tmp';
$data = (time() + $ttl) . "\n" . serialize($value);
if (@file_put_contents($tmp, $data, LOCK_EX) === false) {
return false;
}
return @rename($tmp, $file);
}
public function forget(string $key): void
{
@unlink($this->path($key));
}
}
怎么用
- $cache = new FileCache(__DIR__ . '/../cache');
- $data = $cache->get('home:list'); if ($data === null) { $data = 查库(); $cache->set('home:list', $data, 300); }
- 数据更新时调用 forget 对应的键。
注意
- rename 在同一分区上是原子的,所以不会读到半个文件;跨分区会退化成复制。
- unserialize 传 allowed_classes=false,防止缓存文件被篡改后反序列化出对象。
- 缓存目录放到 Web 根目录外,避免 .cache 文件被直接下载。