使用 PHP 将数据存储在缓存中

问题描述 投票:0回答:1

我有一个活动日历。 每个事件在日历上都有不同的位置。 每次加载页面时,我都会清空事件位置表,并将事件的位置写入表中。

活动地点表是这样的

eventid     location
    1           1
    2           2
    3           1
    4           1
    5           1
    6           2
    7           3
    8           4
    9           5

还涉及一些其他变量,但情况与此非常相似。每个事件都需要知道前一个事件的位置,以便它可以决定自己的位置。

此日历也有不同的视图,并且每个视图都使用相同的技术,因此这不是解决此问题的最健康方法。

问题是; 有什么方法可以将该表的数据存储在缓存或类似的东西上,而不是每次都重写该表。

php caching
1个回答
0
投票

至少可以采用两种方法来缓存此数据。最简单的方法是

serialize()
数据并将其存储在数据库中。当需要检索数据库时,从数据库中查询,
unserialize()
,像以前一样使用。

第二种方法是将 memcache 添加到 PHP 安装中并通过 memcache 函数访问数据。 示例

<?php

$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");

$version = $memcache->getVersion();
echo "Server's version: ".$version."<br/>\n";

$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 123;

$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
echo "Store data in the cache (data will expire in 10 seconds)<br/>\n";

$get_result = $memcache->get('key');
echo "Data from the cache:<br/>\n";

var_dump($get_result);

?>
© www.soinside.com 2019 - 2024. All rights reserved.