Can you store a PHP Array in Memcache?

2019-02-03 03:57发布

Can you store an Array in Memcache?

I would like to store;

  1. A user ID number
  2. A user's photo URL
  3. A users name

Together as an array, someone told me you could and then someone told me you couldn't Which is it?

标签: php memcached
4条回答
Anthone
2楼-- · 2019-02-03 04:14

You can store almost whatever you want in memcached.

See the documentation of memcache::set, which says :

bool Memcache::set(string $key, mixed $var [, int $flag [, int $expire ]] )

var

The variable to store. Strings and integers are stored as is, other types

are stored serialized.

So, yes, you can store an array, or even an object if needed :-)


BTW, it's the same with Memcache::add and Memcache::replace

查看更多
smile是对你的礼貌
3楼-- · 2019-02-03 04:15

max storage size of an item in memcache is 1,048,576 Bytes (1MB), serializing an array does take a bit of space.

if you were to structure your array as simply as:

array(
    [0] => 1,
    [1] => 2,
    [2] => 3
)

key being auto generated and value being the user id.

a serialized array of 5000 users numbered 1-5000 using this structure has a string length of 67792 characters, 50000 users produces an array of 777794 characters.

numbering 100000 to 150000 produces a serialized string of 838917 characters.

so at 50k users (as referenced in your previous question), you will likely be under the 1MB limit. if you have a local cache though (APC, etc...), use that instead, or if for any reason do NOT need all the IDs at once, I would highly suggest splitting up the results or simply using the DB.

also think about the data structure you are storing in memcached. If you are using the cache simply to give you a list of primary keys to lookup, do you need the other data?

查看更多
仙女界的扛把子
4楼-- · 2019-02-03 04:24

Yes.

Memcache::set('someKey', array(
    'user_id' => 1,
    'url' => 'http://',
    'name' => 'Dave'
));

Please see the documentation for very detailed examples.

查看更多
Deceive 欺骗
5楼-- · 2019-02-03 04:25
$memcache = new Memcache;
$memcache->connect('127.0.0.1', 11211) or die ("Could not connect");

$id = $_REQUEST['name'];
$key = md5("SELECT * FROM memc where FirstName='{$id}'");
$get_result = array();
$get_result = $memcache->get($key);

if ($get_result) {
    echo "<pre>\n";
    echo "FirstName: " . $get_result['FirstName'] . "\n";
    echo "Age: " . $get_result['Age'] . "\n";
    echo "</pre>\n";
} else {
    $query="SELECT * FROM memc where FirstName='{$id}'";
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);
    echo "<pre>\n";
    echo "FirstName: " . $row[1] . "\n";
    echo "Age: " . $row[3] . "\n";
    echo "Retrieved from the Database\n";
    echo "</pre>\n";
    $memcache->set($key, $row, MEMCACHE_COMPRESSED, 60);
    mysql_free_result($result);
}

add change database setting according to ur requirement ,tested code please try

查看更多
登录 后发表回答