提问人:Basil 提问时间:10/26/2023 更新时间:10/26/2023 访问量:30
如何在具有限制和参数搜索的 Web 应用程序中正确使用 Memcache?
How to properly use Memcache in web applications with limit and parametric search?
问:
鉴于工具的选择 - memcache,我不确定我的问题最初是否正确,也许我需要看看 Redis,但只要我的项目使用 memcache,那么问题就会在这个工具的上下文中。
所以,我在 PHP 中有一个项目,在那里我使用 memcache 如下所示:
public function findById(int $id): Model
{
$memcacheKey = md5(implode('', [__METHOD__, $id]));
if ($data = memcache()->get($memcacheKey)) {
return $data;
}
// getting data from db
$data = ....;
memcache()->set($memcacheKey, $data, false, 60 * 60 * 24 * 30);
return $data;
}
public function findList(array $params): ModelList
{
// big sql query use $params array
$sql = 'SELECT ... LIMIT ...';
$memcacheKey = md5(implode('', [__METHOD__, serialize($params)]));
if ($data = memcache()->get($memcacheKey)) {
return $data;
}
// getting data from db use $params array
$data = ....;
memcache()->set($memcacheKey, $data, false, 60 * 10);
return $data;
}
我不确定我是否正确或有效地使用缓存。
如果数据库中的一条记录被更新,该怎么办?
我可以手动删除该键下的缓存(因为我可以生成该键的名称)并重新生成该条目的缓存。md5(implode('', ["findById", $id]))
但是条目列表的缓存将保持旧状态,并且仅在缓存过期后才会更新。
我在哪里可以读到如何在 memcache 中解决这个问题? 将参数搜索选择的结果放在 memcache 中通常是否正确? 还是我应该忘记 memcache 并关注 Redis?
答: 暂无答案
评论
findById()
select ... limit 0, 50
findByIds(array $ids) { ... }