Memcache-存储MySQL结果 [英] Memcache - storing mysql results

查看:101
本文介绍了Memcache-存储MySQL结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据库类,该类管理我的应用程序的所有mysql连接.

I have a database class, which manages all my mysql connections for my application.

出于多种原因,我不得不(迟迟没有)实现Memcache.我已经开始弄清楚了,但想确认一件事.

I'm having to (belatedly) implement Memcache, for a number of reasons. I've started to figure it out but want to confirm one thing.

我希望对class进行修改,以使超时设置为默认值.它会查看它是否在内存缓存中,如果不在,则进行查询并存储.

I was hoping to make amendments to class with defaults on timeout. It sees if it's in memcache, if not - make the query and store it.

但是,似乎无法存储mysqli结果(通过此问题 ).这是否意味着您不能在应用程序中使用任何表示$ db-> fetch_assoc()的代码或任何其他常规对象使用的代码?

However, it appears as though you can't store mysqli results (via this question). Does that mean you can't use any code in the application which says $db->fetch_assoc() or any other general object uses?

如果是这样,这是否意味着我们正在讨论全面的代码更改?我想先确认一下.

If so, does this mean we're talking ground up code change across the board? I want to confirm before I put my head in my hands.

推荐答案

您不能存储结果对象,不可以,但是您可以将所有行提取到数组中并存储该数组.如果您需要在其他地方重构代码,则取决于您编写代码的方式以及之前对数据库访问的抽象程度.

You cannot store the result object, no, but you can fetch all rows into an array and store that array. If you need refactoring of your code in other places depends on how you have written your code and how well you have abstracted database access earlier.

例如,如果您具有这样的功能:

For example, if you have a function like this:

function database_result($query) {
   ...
   $result_array = $result->fetchAll();
   return $result_array;
}

然后,您可以在该函数内添加Memcached缓存:

Then you can add Memcached caching inside that function:

function database_result($query, $expire = 60) {
   $memcached_key = 'db:' . $query;
   $cached = $memcached->get($memcached_key);
   if ($memcached->getResultCode() !== Memcached::RES_NOTFOUND) {
       return $cached;
   }
   ...
   $result_array = $result->fetchAll();
   $memcached->set($memcached_key, $result_array, $expire);
   return $result_array;
}

如果您到处都使用原始PDO或MySQLi对象,那么您还有更多工作要做.

If you use the raw PDO or MySQLi object everywhere, then you have more work to do.

这篇关于Memcache-存储MySQL结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆