Beginner’s Introduction to PHP Memcached
- 时间:2020-09-19 10:45:07
- 分类:网络文摘
- 阅读:156 次

php
Querying the Database e.g. MySQL could be very expensive relative to just a cache which is just a key value store . And for SELECT statements, we want to cache the results to speed up the performance. For example, I want to give you x equals to y and next time I ask for x and you give me y – and I want it quick, much faster than the database would return it to me.
The below shows the simple usage of PHP code that connects to a memcached daemon. And if the data is not in the cache, then we will query the MySQL database and store the result in the cache for next time’s retrieval.
1 2 3 4 5 6 7 8 9 | $memcache = memcache_connect(HOST, PORT); $user = memcache_get($memcache, $id); if (is_null($user)) { // cache miss $dbh = new PDO(DSN, USER, PASS); // id is a safe integer type $result = $dbh->query("SELECT * from users WHERE id=$id"); $user = $result->fetch(PDO:FETCH_ASSOC); memcache_set($memcache, $user['id'], $user); // store it in memcached } |
$memcache = memcache_connect(HOST, PORT);
$user = memcache_get($memcache, $id);
if (is_null($user)) { // cache miss
$dbh = new PDO(DSN, USER, PASS);
// id is a safe integer type
$result = $dbh->query("SELECT * from users WHERE id=$id");
$user = $result->fetch(PDO:FETCH_ASSOC);
memcache_set($memcache, $user['id'], $user); // store it in memcached
}The memcached has some expiration cache policy such as LFU (Least Frequent Used) – which evicts the least used cached if cache is full. Alternatively, we can manually expire the caches if the item values are changed. For example, we can combine the cache key with a counter, and increment the counter if we want to expire quite a few items in the cache.
1 2 3 | $cacheKeyForUser = $user['id'] . $counter[$id]; // increment $counter[$id] if $user $id has changed $counter[$id] ++; |
$cacheKeyForUser = $user['id'] . $counter[$id]; // increment $counter[$id] if $user $id has changed $counter[$id] ++;
–EOF (The Ultimate Computing & Technology Blog) —
推荐阅读:广东新闻频道直播-广东电视台新闻频道「高清」 广东电视台移动频道直播「高清」 广东电视台房产频道直播「高清」 广东岭南戏曲频道直播「高清」 嘉佳卡通卫视直播「高清」 广东电视台4K超高清频道直播_南方电视台综艺频道TVS3直播「高清」 广东电视台国际频道直播「高清」 南方购物频道直播_南方购物电视购物直播「高清」 广东电视台现代教育频道直播「高清」 广东经济科教频道直播_南方经济科教频道直播「高清」
- 评论列表
-
- 添加评论