【问题标题】:Using Memcache Directly in Laravel 5 instead of using through Cache在 Laravel 5 中直接使用 Memcache 而不是通过 Cache 使用
【发布时间】:2016-08-24 03:59:27
【问题描述】:

我正在使用本地内存缓存服务器来存储值。如果我将 Memcache 定义为 Cache 的选定驱动程序,它工作正常。在 config/cache.php 但是,如果我在 laravel 外部使用 memcache,则 memcache 访问比在 Laravel 控制器中使用 Cache::get() 快得多。

我需要在 Memcache 中存储大量数据,并且可以跨系统访问。所以我试图直接使用 memcache,但我收到了以下错误。

[2016-08-23 14:11:19] local.ERROR: Symfony\Component\Debug\Exception\FatalThrowableError: Class 'App\Http\Controllers\Memcache' not found in ....

我的代码如下:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use Cache;
use stdClass;
use DB;
use Memcache;


class InternalCommunication extends Controller
{
        public function update_stock_prices_memcache()
        {
                 echo "\n before the memcache obj creation ".microtime(true);
                 $memcache = new Memcache();
                 $memcache->connect('localhost', 11211) or die ("Could not connect");
                 //$res1 = $memcache->set('key1',"Some value 2");
                 $res1 = $memcache->get('key1');
.....

要明确一点——memcache 包已安装并且工作正常,因为我可以通过 Cache: 以及直接从 Laravel 安装外部访问 memcache 来使其工作。 感谢我能得到的任何帮助。

【问题讨论】:

  • new \Memcache;?
  • 是的,试过了。同样的错误:(我使用的是 PHP7,Laravel 5.2,并且我已经安装了 memcached 和 php70-php-pecl-memcache 包。

标签: laravel memcached


【解决方案1】:

按照laravelcache docs,你需要在config/cache.php中设置memcached配置,并指定驱动作为“memcached”使用。

然后,只需使用\Cache,如下例所示。

// to get value
$value = \Cache::get('key');

// to set value
$minuts = 30;
\Cache::put('key', 'value', $minutes);

如果有多个缓存,您还可以在代码中指定驱动程序

$value = \Cache::store('memcached')->get('key');

【讨论】:

  • 这已经为我工作了。我的问题是访问缓存数据大约需要 20 毫秒。如果我在 laravel 外面做同样的事情 - 它工作得更快。因此想知道如何直接使用Memcache。
  • 我明白了,但我相信它应该可以正常工作,而不是有 20 毫秒的延迟
  • 它工作正常。正如我所提到的,我有工作解决方案,但不适合具有如此高访问延迟的系统。我需要存储 1000 个密钥,这些密钥将实时更新——比如每 15-20 秒。所以需要这个缓存并变得更快。谢谢。
【解决方案2】:

我能够找出访问 Laravel 中的内存缓存所需的更改。以下是我现在可以顺利运行的代码。

use Memcached;
        ....
        $memcache = new Memcached;
        $memcache->addServer('localhost', 11211) or die ("Could not connect");
        $res1 = $memcache->get('key1');
        ....

这绝对比使用 memcache 驱动的 Cache::get 快!

【讨论】:

    猜你喜欢
    • 2018-07-20
    • 2017-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多