Автор оригинала: David Wong.
Memcached и Memcached на самом деле одно и то же, но если расширения, используемые в PHP, отличаются, кто-то улучшил использование и производительность memcached примерно в 2009 году написал libmemcached-независимую стороннюю клиентскую библиотеку, а затем memcached. Использование также было значительно улучшено, например, добавлено getMulti () для пакетного получения ключевых значений.
Под окнами, только php __мемкаше.расширение dll может быть установлено и php_memcached.расширение dll не существует, поэтому в Windows можно использовать только Memcached (), но нельзя использовать новый Memcached ().
Кэш памяти класса
$memcache = new Memcache;
$memcache->connect('127.0.0.1', 11211);
$memcache->pconnec('127.0.0.1', 11211);
// Open a persistent connection to the server that will not close after script execution or close () is called$memcache->addServer('123.57.210.55', 11211,$persistent,$weight);
// Add a Memcache server $persistent to the connection pool to persist the connection $weight
Control Bucket Number Upgrade Selected Weight $timeout Represents Continuous Duration$memcache->set('name', 'TK');
// Default storage is not compressed but expires, where strings and values are stored directly, and other types are stored serialized.
Set is actually a set of add and replace methods$memcache->set('email', '[email protected]',MEMCACHE_COMPRESSED,5);
// MEMCACHE_COMPRESSED Sets whether storage is compressed, 5 means that it expires after 5 seconds, but the maximum setting is 2592 000 seconds (30 days).
If set to 0 means never expiring, you can set a future timestamp$memcache->set('info',array('age'=>'26','salary'=>'1000'));
// Arrays can be stored directly, and the storage in redis requires manual serialize () serialization$memcache->add('counter', '10', MEMCACHE_COMPRESSED, 0);
// If the key exists, it returns false, if not, as in the set method, it generates a counter key and assigns 10$memcache->replace ('counter', '10');
// If the key value does not exist, false is returned, and if it does, the value of the replacement counter is 10.$memcache->increment('counter', 3);
// First convert the current value of the element to a value, then subtract the value operation counter key value + 3
If the key does not exist, the return false cannot be used to compress the key operation, otherwise the get key will fail.$memcache - > decrement ('counter', 3); // Operate counter key value - 3, return false if the key does not exist$memcache - > delete ('counter', 3); // operation delete key counter, 3 means deletion within 3 seconds, default is 0 immediately deleted$memcache - > flush (); //flush () immediately invalidates all existing elements
$memcache->getExtendedStats (); // Returns server statistics for a two-dimensional Association data. The key of the array consists of the host: port mode
$memcache - > getServerStatus ('127.0.0.1'); // Getting online/offline status 0 returning to a server means offline non-zero Online$memcache - > getStats (); // Get server statistics
$memcache - > getVersion (); // Return server version information
$memcache->setCompressThreshold ($threshold, $min_saving);
// Open large value automatic compression $threshold setting compression threshold of 2000 bytes, that is, the number of bytes greater than 2K will be compressed.
0.2 between $min_save 0-1 means 20% compression.$memcache->setServerParams('memcache_host', 11211, 1, 15, true, '_callback_memcache_failure');
// $memcache->addServer('memcache_host', 11211, false, 1, 1, -1, false);
Servers have been configured with addServer to reset configuration information using setServer ParamsКласс Memcached
В этом упражнении я установил phpstorm в linux. Смотрите другие мои статьи о разработке и настройке платформы Linux.
$memcached = new Memcached (); //Must install the memcached extension will not install see my related articles
# Explanation of server_key noun# # When the desktop service IP and port are fully connected, a hash ring is formed and $server_key takes effect. # $server_key is just a tag for stored keys, such as three Memcache servers (A B C), specifying server_key 'master-a''master-b''master-c'stores member order logs, etc.
Memcached - > addServer ('192.168.206.128', 11211); // Connect Server$memcached->setOption(Memcached::OPT_COMPRESSION, false); // Configuration storage is not compressed, compressed value is not conducive to increasing and decreasing
$memcached->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true); //
Memcached - > addServers (array (/// add multiple server distribution)
array('192.168.206.128', 11311, 20),
array('192.168.206.128', 11411, 30)
));$memcached - > flush (1); //1 seconds to clear all elements
$memcached->set('name','TK');
$memcached->setByKey('server_master_db','mage','28');
# Specify server_key server_master_db storage key mage
$memcached->setMulti(array('salary'=>'3000','email'=>'[email protected]'));
// Storing multiple elements
$memcached->setMultiByKey('server_master_db',
array('salary'=>'3000','email'=>'[email protected]'));
//'server_master_db'server stores multiple elements$memcached - > add ('name','TK'); the // key name does not exist to add value otherwise the addition fails
$memcached->addByKey('server_master_db','mname','MTK');$memcached - > append ('key','-816'); // key value followed by a string - 816
$memcached->appendByKey('server_master_db','mname','-923');Memcached - > prepend ('name','pre-'); and # append data to an existing element
$memcached->prependByKey('server_master_db','name','pre-') ;
# Use server_key to map keys freely to the specified server to append data to an existing element$memcached->get('name');
$memcached->get('name',null,$cas);
# The second parameter specifies the cache fallback function and does not specify the pass null
# If the element is found and the return variable $cas is returned internally by referencing the variable
Memcached - > getByKey ('server_master_db','mname'); # Retrieve elements from specific serversMemcached - > getAllKeys (); // bug I returned unanimously false
$memcached->cas($cas, 'name', 'TangKang');
# To get the $cas variable, use the $memcached - > get ('name', null, $cas) method
# It can write the value only if the value corresponding to the key has not been modified by other clients after the last value is taken by the current client.
# This is a very important advantage of Memcached extensions over Memcached extensions.
Under such a system-level conflict detection mechanism (optimistic lock) provided by Memcache itself, we can ensure data security under high concurrency.
$memcached->casByKey($cas,'server_master_db', 'name', 'TangKang');$memcached->increment('age','1');
# Increase the value of a numeric element. If the value of an element is not a numeric type, treat it as 0.
$memcached->incrementByKey('server_master_db','age','1');
# Servers for identifying stored and read values$memcached->decrement('age','1');
# Reduce the value of a numeric element. If the value of an element is not a numeric type, treat it as zero.
$memcached->decrementByKey('server_master_db','age','1');
# Servers for identifying stored and read values$memcached->getDelayed(array('name', 'age'), true, null);
# Request multiple elements, and if with_cas is set to true, the CAS tag for each element is requested at the same time
Specify a result callback instead of explicit fetch results
$memcached->getDelayedByKey('server_master_db',array('name', 'age'), true, null);$memcached->fetch(); # Use with $memcached - > getDelayed () to fetch the next result from the last request $memcached->fetchAll(); # Grab all the remaining results in the result set of the last request
Memcached - > getMulti (array ('name','age'); # retrieves multiple elements
$memcached->getMultiByKey('server_master_db',array('mname', 'mage'));
# Retrieving multiple elements from a specific server
# Use with $this - > memcached - > fetchAll ()$memcached->getOption(Memcached::OPT_COMPRESSION); # Get the option value of Memcached
$memcached->getResultCode() ; # Returns the result code of the last operation, Memcached:: RES_NOTSTORED $memcached->getResultMessage() ; # Returns the result description message for the last operation
Memcached - > getServerByKey ('server_master_db'); # Gets the server information mapped by a key
$memcached - > getServerList (); # Get the list of servers in the server pool
$memcached - > getStats (); # Get server pool statistics
$memcached - > getVersion (); # Get version information for all servers in the server poolMemcached - > isPersistent (); # Determine whether the current connection is a long connection?
$memcached->replace('name','pre-julylovin') ;
# set () is similar, but if the server does not have a key, the operation will fail.
$memcached->replaceByKey('server_master_db','name','pre-julylovin') ;
# setBykey () is similar, but if the server does not have a key, the operation will fail.Memcached - > resetServerList (); // Clear server pool information
$memcached->setOption(Memcached::OPT_PREFIX_KEY, "widgets") ; # Set a memcached option $memcached->setOptions(array()) ; # Set a memcached option
$memcached->setSaslAuthData($username , $password ) ; # The setSaslAuthData method does not exist
$memcached->touch('name', 10) ;
# The key name expires after 10 seconds (only within 30 days). Please set a timestamp after 30 days.
$memcached->touchByKey('server_master_db','name',10) ;$memcached->delete('age',10);
# Delete an element in 10 seconds (seconds/timestamp). The key already exists in the deletion queue
The get, add, replace commands corresponding to this key are not available until they are deleted.
$memcached->deleteByKey('server_master_db','age');
$memcached - > deleteMulti (array ('age','name'); # incoming array deletes multiple keys
$memcached->deleteMultiByKey('server_master_db',array('age','name'));$memcached - > quit (); # Close all open links
Оригинал: “https://developpaper.com/php-manual-of-memcache-memcached-manuscript-edition/”