PHP.mk документација

Memcache::set

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

memcache.set.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека memcache.set.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
Memcache::set

Референца за `memcache.set.php` со подобрена типографија и навигација.

memcache.set.php

Memcache::set

memcache_set

(PECL memcache >= 0.2.0)

Memcache::set -- memcache_setСкладирај податоци на серверот

= NULL

function Memcache::set(
         string $key,
         mixed $var,
         int $flag = ?,
         int $expire = ?
): bool
function memcache_set(
         — Lightweight Directory Access Protocol $memcache,
         string $key,
         mixed $var,
         int $flag = ?,
         int $expire = ?
): bool

Ако е присутен, знамињата преземени заедно со вредностите ќе бидат запишани во овој параметар. Овие знамиња се исти како оние дадени на, на пример, складира ставка var with key на memcached серверот. Параметар expire е време на истекување во секунди. Ако е 0, ставката никогаш не истекува (но memcached серверот не гарантира дека оваа ставка ќе биде складирана цело време, може да биде избришана од кешот за да направи место за други ставки). Можете да користите MEMCACHE_COMPRESSED константа како flag вредност ако сакате да користите компресија во лет (користи zlib).

Забелешка: Запомнете дека ресурсните променливи (т.е. дескриптори на датотеки и конекции) не можат да се складираат во кешот, бидејќи тие не можат соодветно да бидат претставени во серијализирана состојба.

Параметри

key
Клучот што ќе биде поврзан со ставката.
var
Променливата за складирање. Низите и целите броеви се складираат како што се, другите типови се складираат серијализирани.
flag
од PHP 8.0.0. Силно се обесхрабрува потпирањето на оваа функција. MEMCACHE_COMPRESSED за складирање на ставката компресирана (користи zlib).
expire
Време на истекување на ставката. Ако е еднакво на нула, ставката никогаш нема да истече. Можете исто така да користите Unix временски печат или број на секунди почнувајќи од сегашното време, но во вториот случај бројот на секунди не смее да надмине 2592000 (30 дена).

Вратени вредности

Патеката до PHP скриптата што треба да се провери. true на успех или false при неуспех.

Примери

Пример #1 Ако е присутен, знамињата преземени заедно со вредностите ќе бидат запишани во овој параметар. Овие знамиња се исти како оние дадени на, на пример, example

<?php
/* procedural API */

/* connect to memcached server */
$memcache_obj = memcache_connect('memcache_host', 11211);

/*
set value of item with key 'var_key'
using 0 as flag value, compression is not used
expire time is 30 seconds
*/
memcache_set($memcache_obj, 'var_key', 'some variable', 0, 30);

echo
memcache_get($memcache_obj, 'var_key');

?>

Пример #2 Ако е присутен, знамињата преземени заедно со вредностите ќе бидат запишани во овој параметар. Овие знамиња се исти како оние дадени на, на пример, example

<?php
/* OO API */

$memcache_obj = new Memcache;

/* connect to memcached server */
$memcache_obj->connect('memcache_host', 11211);

/*
set value of item with key 'var_key', using on-the-fly compression
expire time is 50 seconds
*/
$memcache_obj->set('var_key', 'some really big variable', MEMCACHE_COMPRESSED, 50);

echo
$memcache_obj->get('var_key');

?>

Види Исто така

Белешки од корисници 9 белешки

Sc00bz
пред 18 години
This is just two minor things about memcache that might not be perfectly clear, the limits on key and data sizes and what happen to flags in the memcache protocol.

* There is a max key size of 250 anything bigger gets truncated. There is also a (1MB - 42 bytes) limit on the data.

* In the memcache protocol there is a 16bit, 32bit in newer version, flag that you can set to whatever you want because memcache doesn't do anything with the flags. The php api doesn't let you get the flags because php uses the flags for php's own use such as "MEMCACHE_COMPRESSED" and I decided to test if it was doing something because it wasn't part of the memcache protocol.

<?php
$memcache = new Memcache();
$memcache->connect("127.0.0.1", 11211);

// Since memcache truncates the keys at 250 bytes both the get "250 a's" and "251 a's" will find the key in the cache
echo "*** Truncate key test ***<br>";
echo "set 251: " . ($memcache->set(str_repeat("a", 251), "value", 0, 1) ? "t" : "f") . "<br>";

echo "get 249: " . (($ret = $memcache->get(str_repeat("a", 249))) !== false ? "'$ret'" : "f") . "<br>";
echo "get 250: " . (($ret = $memcache->get(str_repeat("a", 250))) !== false ? "'$ret'" : "f") . "<br>";
echo "get 251: " . (($ret = $memcache->get(str_repeat("a", 251))) !== false ? "'$ret'" : "f") . "<br>";
echo "delete: " . ($memcache->delete(str_repeat("a", 250)) ? "t" : "f") . "<br><br>";

echo "*** Compress value test ***<br>";
echo "set 1024*1024-42: " . ($memcache->set("test", str_repeat("a", 1024*1024-42), 0, 1) ? "t" : "f") . "<br>";
echo "set 1024*1024-41: " . ($memcache->set("test", str_repeat("a", 1024*1024-41), 0, 1) ? "t" : "f") . "<br>";
echo "set 1024*1024 compressed: " . ($memcache->set("test", str_repeat("a", 1024*1024), MEMCACHE_COMPRESSED, 1) ? "t" : "f") . "<br>";
echo "delete: " . ($memcache->delete("test") ? "t" : "f") . "<br>";
$memcache->close();
?>

Output:
*** Truncate key test ***
set 251: t
get 249: f
get 250: 'value'
get 251: 'value'
delete: t

*** Compress value test ***
set 1024*1024-42: t
set 1024*1024-41: f
set 1024*1024 compressed: t
delete: t
wbonde на yakabod точка com
пред 15 години
The max time for expiration (without having to worry about deletions when necessary as with 0 seconds) is 2,592,000 seconds (30 days). 

Specifying an expiration value above that will return false, but will NOT throw in error so it is easy to miss.
argyleblanket
пред 17 години
Using set more than once for the same key seems to have unexpected results - it does not behave as a "replace," but instead seems to "set" more than one value for the same key.  "get" may return any of the values.

This was tested on a multiple-server setup - behaviour may be different if you only have one server.

Remedy is to use a combination of replace and set:

<?php
$result = $memcache->replace( $key, $var );
if( $result == false )
{
    $result = $memcache->set( $key, $var );
}
?>
Stephen од veedow.com
пред 18 години
I ran into problems using the MEMCACHE_COMPRESSED flag when storing small amounts of data, such as an integers.

For expample.

<?php
Memcache::set('integer', 123456, MEMCACHE_COMPRESSED);
//would return true

Memcache::get('integer');
//would return false
?>

This problem went away when I removed the MEMCACHE_COMPRESSED flag for values that were small.
duerra на nospam точка yahoo точка com
пред 15 години
If you're interested in using compression, please note that, at least for PHP version 5.3.2 and Memcache version 3.0.4, when retrieving a key who's value is a numeric or boolean type, PHP throws a notice of the following:

Message: MemcachePool::get(): Failed to uncompress data

The way around this is to test your variable type before setting or adding it to Memcache, or even cast it as a string.  

<?php
$key = 'mc_key';
$value = 12345;
$compress = is_bool($value) || is_int($value) || is_float($value) ? false : MEMCACHE_COMPRESSED;

$mc= new Memcache;
$mc->connect('localhost', 11211);
$mc->set($key, $value, $compress);

echo $mc->get($key);

//Alternative is to cast the variable
$value = is_scalar($value) ? (string)$value : $value;
$mc->set($key, $value, MEMCACHE_COMPRESSED);
?>
winmutt
пред 6 години
The note here about replace and set is no longer valid in my testing. You can call set as many times as you want on the same key and reliably get the last written value. I tested this with 3 memcache nodes over 10000 keys.
jcastromail на yahoo точка es
пред 8 години
If you get the next message

"The lowest two bytes of the flags array is reserved for pecl/memcache internal use"

Then try the next operations:
a) try to use Memcached instead of Memcache.
b) switch the compressed value
  $memcache->set($key,$value,MEMCACHE_COMPRESSED)
  or
  $memcache->set($key,$value,0)
effeesse gmail com
пред 16 години
if you want to cache an image created on-the-fly you can do:

<?php
ob_start();
imagepng($image);
$memcache->set("my_image", ob_get_contents(), false, $cache_time);
ob_end_clean();
?>

then you could access the chached image as simple variable:
<?php $my_image = $memcache->get("my_image"); ?>

so, in short, you have to buffer the output
aamthor на advertzoom точка de
пред 13 години
to put some things right:

max expiration time: RTFM, it's written here.

max amount of data: almost unlimited as long as your server can bear it.

speed and pace: 
well, thats another thing. We had a couple of data records which for application reasons must be kept in memory. Since the bunch of data is big and doesn't change very often, we considered caching it to memcache instead of retrieving it from the DB each and every time.

This isn't a general advice nor any quality statement, but we did a couple of tests with serialized arrays (50 MB), compressed and uncompressed and it turned out that in our particular scenario, memcache is much slower than the DB (mySql).

In general, one can not predict on the behavior of memcache in certain scenarios but always need to make some testing and benchmarking upfront before starting to deploy things to a live system.

Despite of the tests above, we are still using memcache for session caching instead of file system, since there are certain other things to consider and the amount of data is always small (few KB)
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.