【问题标题】:Memcached/XCache caching of SQL results?SQL 结果的 Memcached/XCache 缓存?
【发布时间】:2012-11-16 01:25:47
【问题描述】:

我刚刚为社交网站设计了一个管理控制台。我的老板现在要我缓存构建这些结果的几个 MySQL 查询的结果(24 小时)。该站点使用 Memcached(带有 Wordpress W3 总缓存)和 XCache。我想知道最好的方法是什么。

这是一个此类查询的示例以及我如何获得结果(基本上我返回的是用户的汇总统计信息,这意味着我的结果相当简单,例如:

//users who registered in last 365 days
$users_reg_365 = "select ID
from wp_users
where user_registered > NOW() - interval 365 day";

然后使用 wpdb 查询类获取结果:

$users_reg_365 = $wpdb->get_results($users_reg_365);

然后在仪表板中显示结果:

<li><?php echo "Total users who registered within last 365 days: <span class='sqlresult'>" . sizeof($users_reg_365) . "</span>"; ?></li>

我对 Memcached/XCache 的理解是它基本上是存储字符串的,所以只缓存 sizeof($users_reg_365) 有意义吗?

最后一个问题是我们的 Wordpress 网站使用 W3 总缓存,它利用了 Memcached,老板让我不要使用 Memcached 而是使用 XCache,但我发现文档有点混乱。解决这个问题的最佳方法是什么?是否可以告诉 SQL 本身“记住”某些这样的查询,或者内存缓存是要走的路?

谢谢!

【问题讨论】:

  • XCache 是一个操作码缓存器,对吧?这很有帮助,因为您不必重新解析您的 php 代码。可能是错的。

标签: php mysql wordpress memcached xcache


【解决方案1】:

您可以在此处找到有关两者差异的更多信息: Difference between Memcache, APC, XCache and other alternatives I've not heard of

举个例子

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

// cache 24hrs
$cache_expire = 86400;


// users is your key
$users_reg_365 = $m->get('users_reg_365');
if (empty($users_reg_365)) {
    $users_reg_365 = "select ID from wp_users where user_registered > NOW() - interval 365 day";
    $m->set('users_reg_365', $cache_expire);
}

如果您需要在午夜准确刷新缓存,请更改 $cache_expire 的值。

你可以参考memcached的完整参考 http://www.php.net/manual/en/memcached.get.php

【讨论】:

    【解决方案2】:

    嗯。我不确定您的缓存是如何在 WordPress 中配置的。如果您将 WordPress 的对象缓存设置为使用 Memcache(d)/XCache 进行持久缓存,您可以执行类似的操作:

    $key = 'custom-key-to-look-up-later';
    $data = sizeof( $users_reg_365 );
    $group = 'group-id';
    $expire = 60 * 60 * 24 // time in seconds before expiring the cache.
    
    wp_cache_set( $key, $data, $group, $expire );
    

    稍后您可以像这样查找该值:

    $data = wp_cache_get( $key, $group );
    
    if( ! is_wp_error( $data ) )
        // the data is good. do something with it.
    

    你可以在here找到这些函数的文档。

    不过,在开始之前,请确保 WordPress 已设置为与 Memcache(d) 或 XCache 一起使用。 :)

    【讨论】:

      【解决方案3】:

      如果您想存储任何数组的结果,只需对其进行序列化/jsonencode 并按原样存储..

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-06
        • 2013-12-03
        • 2017-01-04
        • 1970-01-01
        • 2015-10-10
        • 1970-01-01
        • 1970-01-01
        • 2010-11-22
        相关资源
        最近更新 更多