简体   繁体   中英

Laravel Cache issue with Memcached

I have one strange issue while using Memcached with Laravel. On my local environment I'm using Windows and because there is no Memcached for Windows I use the file cache driver locally. For the production server, we have Memcached installed and I use different config there and use the Memcached driver. The code is the same. Here is my issue with Memcached. Here is one simple code:

$cacheKey = "test_key";       
$hasCache =  Cache::has($cacheKey);
$value = "";

if($hasCache)
{
    $value = Cache::get($cacheKey);
}

$isAdded = Cache::add($cacheKey, "test_value", 60);

$isAdded is always true (it should be true only the first time), so the cache is added, but $hasCache is always false and $value is always empty. It's like the value is deleted right after it is added to the cache

Locally it works fine, the issue appears only on the production server. There are no exceptions thrown. I tried switching to the file driver on the production server and it works as it should, so the issue is with the memcached driver.

I'm having hard time debugging this, so if anyone had similar issue, I'd appreciate the help :)

In your case there, of course you will always have $idAdded == true there, doesn't matter if you have $value = "" or $value = "test_value" , your are still assigning a value to the key.

I've also had some issues with Memcached and Laravel, though I think it's more because I don't understand Memcached all to well.

However, I recommend using the Cache::remember() -function instead of checking and setting the cache in two different steps. Memcached has played nice with me since I started using it instead, so in your example:

$cacheKey = 'test_key';

$value = Cache::remember($cacheKey, 60, function(){
    $value = 'test_value';
    return $value;
});

Also, have you checked that Memcached is actually running, and you have supplied the right connection?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM