Basic knowledge of Memcache

1. What is Memcache

  memcache is a distributed high-speed cache database system. By maintaining a unified huge hash table in memory, it can be used to store data in various formats, including images, videos, files, and database retrieval results. Simply put, the data is transferred to the memory and then read from the memory, thereby greatly improving the reading speed. It is currently used by many websites to improve the access speed of the website. Memcache official website: http://memcached.org

  Memcache usage scenarios:
   1. Non-persistent storage: low requirements for data storage
   2. Distributed storage: not suitable for stand-alone use
   3. Key/Vaulue storage: simple format, not supported List, Array data format
Basic knowledge of Memcache

  features and limitations:
   1. There is no limit to the amount of item data that can be maintained in Memcached, as long as the memory is sufficient.
   2. Memcached single process can use up to 2G of memory in 32-bit system. If it is in 64-bit system, there is no limit. This is due to 32-bit system limitation but the process can use up to 2G of memory. To use more memory, you can divide it into multiple The port enables multiple Memcached processes.
   3. The maximum data expiration time of 30 days, set to permanent will also expire at this time, constant REALTIME_MAXDELTA 60 60 24*30 control
   4. The maximum key length is 250 bytes, longer than this length can not be stored, constant KEY_MAX_LENGTH control
   5. The maximum data of a single item is 1MB, and the data exceeding 1MB will not be stored. The constant POWER_BLOCK 1048576 is used for control, which is the default slab size
   6. The maximum number of simultaneous connections is 200, which is controlled by freetotal in conn_init(), and the maximum number of soft connections is 1024, which is controlled by settings.maxconns=1024.
   7. The parameters related to space occupation: settings.factor = 1.25, settings .chunk_size = 48, affecting slab data occupation and stepping method

   memcached is a non-blocking socket communication service, based on the libevent library, because it is non-blocking, the memory read and write speed is very fast.

   Memcached is divided into server-side and client-side, multiple server-side and client-side can be configured, and it is widely used in distributed services.

   Memcached is very effective as a small-scale data distributed platform.

   memcached is one-to-one correspondence between key and value. The default maximum size of key cannot exceed 128 bytes, and the default size of value is 1M, which is one slabs. If you want to store a value of 2M (continuous), you cannot use two slabs, because two slabs It is not continuous and cannot be stored in memory, so the size of slabs needs to be modified. When multiple keys and values ​​are stored, even if the slabs are not used up, no other data will be stored.

Second, the difference between Mecached and memcache and memcached

先来解释下标题中三种写法:首字母大写的Mecached,指的是Memcached服务器,就是独立运行Memcached的后台服务器,用作存储缓存数据的“容器”。Memcached是可以独立在web服务器之外任何服务器,甚至可以是集群。memcached和memcache是Memcached的客户端,通过二者访问Memcached服务器,向容器存取数据。二者用途一致,但在用法上稍有差异。如下:

  1. memcache was first developed in February 2004, and the last update was in April 2013, while memcached was first developed in January 2009, and finally was updated in January 2014. Therefore, the history of memcache is earlier than memcached. For more information, please refer to:
  memcache: http://pecl.php.net/package/memcache
  memcached: http://pecl.php.net/package/memcached
  2. memcache is a native version, completely in the PHP framework Developed to support the coexistence of OO (object-oriented) and non-OO interfaces, memcahed is based on libmemcached and only supports OO interfaces. This means that you are not required to install other things when memcache is extended, but you will be required to install libmemcached when you install memcached. Because libmemcached is a C client of memcache, it has the advantages of low memory and thread safety. It is said that Sina Weibo has fully replaced PHP's memcache with PHP's memcached before. With high concurrency, the stability has been decisively improved.
  3. Memcached has a nice place, that is, the flag is not set during operation, but has a unified setOption() function to set, take adding cached data as an example:

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

#memcached:
public  bool  Memcached::add(string   $key ,mixed  $value  [, int    $expiration])

As can be seen from the respective add methods above, the third parameter in the add method of memcache represents whether to compress the data, so if my cache needs to set an expiration time, but the flag parameter is in front, I have to do it every time Set the flag! In memcached, setOption() is used for unified settings (compression is turned on by default).
  4. Memcached supports more memcache protocols than memcache, which probably means that memcached has more methods, such as getMulti() and setMulti() functions are very useful, but memcache does not support them. More methods can be found in the official PHP manual: memcache: http://php.net/manual/zh/book.memcache.php
memcached: http://php.net/manual/zh/book.memcached.php
  5 The big difference is that memcached supports Binary Protocol, but memcache does not, which means that memcached will have higher performance. But many people say that memcached does not support long links. This is not the case. Please
  Basic knowledge of Memcache
  refer to the official manual: http://php.net/manual/zh/memcached.construct.php It is clearly stated above when using long links. . . . . Therefore, memcached is able to achieve long connections.
  6. There is also a difference in the algorithms used by the two to implement some of the same functions. For example, everyone knows that the "consistent hash algorithm" is that when storage nodes are added or deleted, it has less impact on the data stored on memcached An algorithm, which can be used in the two extension libraries of PHP, but the setting method is different.

    memcache
    修改php.ini添加:
    [Memcache]
    Memcache.allow_failover = 1
    ......
    ......
    Memcache.hash_strategy = consistent
    Memcache.hash_function = crc32
    ......
    ......
    或在PHP中使用 ini_set 方法
    Ini_set('memcache.hash_strteagy ','standrad');
    Ini_set('memcache.hash_function','crc32');

    memcached
    $mem = new memcached();
    $men->setOption(Memcached::OPT_DISTRIBUTION,Memcached::DISTRIBUTION_CONSISTENT);
    $mem->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE,true);

Summarize the description of the three relationships: Memcahed is, for example, a reservoir (container), memcache is a plastic tube, and memcached is a PVC tube. We can use plastic pipes or PVC pipes to fill or fetch water from the reservoir. The method used varies from person to person. PVC pipes are obviously faster than plastic pipes in transporting water, and they can be equipped with valves, openings and branches, etc. There are more patterns than plastic tubes. A conclusion can also be drawn from the above analysis: memcached is better than memcache, so in the future development process, try to use memcached.

3. Install Memcache server and client under Linux

Basic knowledge of Memcache
Basic knowledge of Memcache
Basic knowledge of Memcache
Basic knowledge of Memcache
Basic knowledge of Memcache
Basic knowledge of Memcache

Four, use Memcache in PHP

  System class: addServer, addServers, getStats, getVersion
  Data class: add, set, delete, flush, replace, increment, get
  Advanced class: setMulti, deleteMulti, getMulti, getResultCode, getResultMessage

<?php
$m = new  Memcache();
$array  =  array(
                            array('127.0.0.1',11211),
                            array('127.0.0.2',11211),
                );
$m->addServers($array);        //连接服务端
print_r($m->getStats());           //查看状态
print_r($m->getVersion());       //查看版本号
//两个add,后面一个不会覆盖掉前面一个
$m->add('mkey','mvalue',600);
$m->add('mkey','mvalue2',600);
echo $m->get('mkey');
//replace覆盖前面相同的key
$m->replace('mkey','mvalue2',600);
//set方法既可以直接覆盖也会替换覆盖
$m->set('mkey','mvalue',600);
//删除
$m->delete('mkey');
//清空全部缓存
$m->flush();
//每次加5和减5操作
$m->increment('num',5);
echo  $m->get('num');
$m->decrement('num',5);
//setMulti第一个参数是存储的数据,第二个是过期时间
$data1 = array(
                'key'      =>       'value',
                'key2'    =>       'value2',
);
$m->setMulti($data,0);
$result = $m->getMulti(array('key','key2'));
print_r($result);
//一次性删除多条数据
$m->deleteMulti(array('key','key2'));
print_r($result);
//错误编码与错误内容,官方参考文档:https://www.php.net/manual/zh/memcached.getresultcode.php
echo  $m->getResultCode();
echo  $m->getResultMessage();

  

Guess you like

Origin blog.51cto.com/bin06/2642488