Home Backend Development PHP Tutorial How to use Memcached commands in PHP

How to use Memcached commands in PHP

Mar 27, 2018 am 09:33 AM
memcached php Order

In this article, Pig Mastiff shares with you how to use the Memcached command in PHP and makes a summary. I hope it can help everyone.

Portal: http://www.php.net/manual/zh/book.memcached.php
There is no memcached extension under windows, only memcache extension. Personal test, there is still a big difference between the two. So it is recommended to do it in linux.

<?php    $mem = new Memcached();    //添加一台服务器资源
    $mem->addServer(&#39;127.0.0.1&#39;, &#39;11211&#39;);    //添加多台,分布式存储,第三个参数为权重值
    /*
            $servers = array(
            array(&#39;127.0.0.1&#39;, 11211, 33),
            array(&#39;127.0.0.2&#39;, 11211, 67),
        );
        $res = $mem->addServers($servers);

    */

    //设置:键  值  过期时间(秒)
    $mem->set(&#39;name&#39;, &#39;huangyuxin&#39;, 5);    //注意:最大生命周期可设置为60*60*24*30 三十天的时间 
    //再往后的话要加上时间戳 time()+60*60*24*31(三十一天)

    //获取值
    $value = $mem->get(&#39;name&#39;);    //添加值,如果存在此键,false
    $result = $mem->add(&#39;name&#39;,&#39;zhangsan&#39;);    //追加: 键 值 ,追加在一个已经存在的值得后面,不存在也为false
    //setOption 这一句必须加上,不然追加不上
    //prepend 前面追加
    //如果Memcached::OPT_COMPRESSION常量开启,这个操作会失败,并引发一个警告,因为向压缩数据 后追加数据可能会导致解压不了。
    $mem->setOption(Memcached::OPT_COMPRESSION, false);    $mem->append(&#39;name&#39;,&#39;haha&#39;);    $value = $mem->get(&#39;name&#39;);    //这个是减掉元素的值,两个参数,第二个参数决定减掉数值几,默认是 1 ,increment 是加
    $mem->set(&#39;age&#39;, 12, 30);    $mem->decrement(&#39;age&#39;);    $mem->decrement(&#39;age&#39;,2);    $value = $mem->get(&#39;age&#39;);    //删除元素
    $mem->delete(&#39;age&#39;);    $mem->delete(&#39;age&#39;,60);    /*
    注意:
        服务端在这段时间拒绝对这个key的add和replace命令. 
        由于这个时间段的存在, 元素被放入一个删除队列
        表明它不可以通过get命令获取到值
        但是同时 add和replace命令也从服务端内存删除
    (表明元素会被立即删除并且之后对这个 key的存储命令也会成功)
*/

    //删除多个
    $mem->add(&#39;age&#39;, 12, 60);    $mem->add(&#39;name&#39;, &#39;huangyuxin&#39;, 60);    $res = $mem->deleteMulti(array(&#39;age&#39;,&#39;name&#39;));    //作废 :flush不会 真正的释放已有元素的内存, 而是逐渐的存入新元素重用那些内存。
    $mem->flush(10);//10秒内清除元素

    //获取所有键
    $mem->getAllKeys();    /*
        Memcached::getDelayed()向Memcached服务端发出一个检索
        keys指定的多个 key对应元素的请求。这个方法不会等待响应而
        是立即返回。当你需要收集元素值时, 调Memcached::fetch()
        或 Memcached::fetchAll()。如果with_cas设置为true,会
        同时请求每个元素的CAS标记。
    */
    $m->set(&#39;int&#39;, 99);    $m->set(&#39;array&#39;, array(11, 12));    $m->getDelayed(array(&#39;int&#39;, &#39;array&#39;), true);
    var_dump($m->fetchAll());    //获取多个值的信息
    $mem->set(&#39;age&#39;, 12, 60);    $mem->set(&#39;name&#39;, &#39;huangyuxin&#39;, 60);    $res = $mem->getMulti(array(&#39;age&#39;, &#39;name&#39;));    //设置多个键
    $items = array(    &#39;key1&#39; => &#39;value1&#39;,    &#39;key2&#39; => &#39;value2&#39;,    &#39;key3&#39; => &#39;value3&#39;,
);    $mem->setMulti($items);    $res = $mem->get(&#39;key1&#39;);//value

    //返回系统常量
    var_dump($mem->getOption(Memcached::OPT_COMPRESSION));    //返回最后一次操作的结果描述消息
    $mem->add(&#39;a&#39;, &#39;bar&#39;); // first time should succeed
    echo $mem->getResultMessage(), "\n"; //SUCCESS

    //查看此key在哪个服务器上
    $mem->add(&#39;a&#39;, &#39;bar&#39;); // first time should succeed
    $res = $mem->getServerByKey(&#39;a&#39;);    //array(3) { ["host"]=> string(9) "127.0.0.1" ["port"]=> int(11211) ["weight"]=> int(0) } 

    //返回服务器列表
    var_dump($mem->getServerList());    //返回服务器状态
    var_dump($mem->getServerList());    //服务器版本
    print_r($mem->getVersion());    //判断是否是持久链接
    $res = $mem->isPersistent();    //Memcached::replace()和Memcached::set()类似,但是如果 服务端不存在key, 操作将失败。
    $m->set(&#39;hh&#39;, &#39;aaaa&#39;);    $m->replace(&#39;hh&#39;, &#39;bbbb&#39;);    $res = $m->get(&#39;hh&#39;);    //删除从已知的服务器列表中的所有缓存服务器,重置回空。
    $mem->resetServerList();    //对某一key重新设置生命周期
    $m->set(&#39;aaaa&#39;, &#39;aaaa&#39;, 600);    $m->touch(&#39;aaaa&#39;, 5);    $value= $m->get(&#39;aaaa&#39;);    //关闭打开的链接
    $m->quit();

    var_dump($value);
Copy after login
Copy after login

The following suffix is ​​ByKey, which is generally used by multiple Memcached Servers. If you master the above commands, you will basically use them below.

touch->touchByKey
setMulti->setMultiByKey
getMulti->getMultiBykey
replace->replaceByKey
append->appendByKey
prepend->prependByKey
getServerByKey
getdelay->getDelayedByKey 
increment->incrementByKey
decrement->decrementByKey
add->addByKey
get->getByKey
delete->deleteMultiByKey
Copy after login
Copy after login
$m->addByKey(&#39;指定服务器&#39;,&#39;键&#39;,"值")
Copy after login
Copy after login

Waiting more than taking action is equal to waiting to die.

Portal: http://www.php.net/manual/zh/book.memcached.php
There is no memcached extension under windows, only memcache extension. Personal test, there is still a big difference between the two. So it is recommended to do it in linux.

<?php    $mem = new Memcached();    //添加一台服务器资源
    $mem->addServer(&#39;127.0.0.1&#39;, &#39;11211&#39;);    //添加多台,分布式存储,第三个参数为权重值
    /*
            $servers = array(
            array(&#39;127.0.0.1&#39;, 11211, 33),
            array(&#39;127.0.0.2&#39;, 11211, 67),
        );
        $res = $mem->addServers($servers);

    */

    //设置:键  值  过期时间(秒)
    $mem->set(&#39;name&#39;, &#39;huangyuxin&#39;, 5);    //注意:最大生命周期可设置为60*60*24*30 三十天的时间 
    //再往后的话要加上时间戳 time()+60*60*24*31(三十一天)

    //获取值
    $value = $mem->get(&#39;name&#39;);    //添加值,如果存在此键,false
    $result = $mem->add(&#39;name&#39;,&#39;zhangsan&#39;);    //追加: 键 值 ,追加在一个已经存在的值得后面,不存在也为false
    //setOption 这一句必须加上,不然追加不上
    //prepend 前面追加
    //如果Memcached::OPT_COMPRESSION常量开启,这个操作会失败,并引发一个警告,因为向压缩数据 后追加数据可能会导致解压不了。
    $mem->setOption(Memcached::OPT_COMPRESSION, false);    $mem->append(&#39;name&#39;,&#39;haha&#39;);    $value = $mem->get(&#39;name&#39;);    //这个是减掉元素的值,两个参数,第二个参数决定减掉数值几,默认是 1 ,increment 是加
    $mem->set(&#39;age&#39;, 12, 30);    $mem->decrement(&#39;age&#39;);    $mem->decrement(&#39;age&#39;,2);    $value = $mem->get(&#39;age&#39;);    //删除元素
    $mem->delete(&#39;age&#39;);    $mem->delete(&#39;age&#39;,60);    /*
    注意:
        服务端在这段时间拒绝对这个key的add和replace命令. 
        由于这个时间段的存在, 元素被放入一个删除队列
        表明它不可以通过get命令获取到值
        但是同时 add和replace命令也从服务端内存删除
    (表明元素会被立即删除并且之后对这个 key的存储命令也会成功)
*/

    //删除多个
    $mem->add(&#39;age&#39;, 12, 60);    $mem->add(&#39;name&#39;, &#39;huangyuxin&#39;, 60);    $res = $mem->deleteMulti(array(&#39;age&#39;,&#39;name&#39;));    //作废 :flush不会 真正的释放已有元素的内存, 而是逐渐的存入新元素重用那些内存。
    $mem->flush(10);//10秒内清除元素

    //获取所有键
    $mem->getAllKeys();    /*
        Memcached::getDelayed()向Memcached服务端发出一个检索
        keys指定的多个 key对应元素的请求。这个方法不会等待响应而
        是立即返回。当你需要收集元素值时, 调Memcached::fetch()
        或 Memcached::fetchAll()。如果with_cas设置为true,会
        同时请求每个元素的CAS标记。
    */
    $m->set(&#39;int&#39;, 99);    $m->set(&#39;array&#39;, array(11, 12));    $m->getDelayed(array(&#39;int&#39;, &#39;array&#39;), true);
    var_dump($m->fetchAll());    //获取多个值的信息
    $mem->set(&#39;age&#39;, 12, 60);    $mem->set(&#39;name&#39;, &#39;huangyuxin&#39;, 60);    $res = $mem->getMulti(array(&#39;age&#39;, &#39;name&#39;));    //设置多个键
    $items = array(    &#39;key1&#39; => &#39;value1&#39;,    &#39;key2&#39; => &#39;value2&#39;,    &#39;key3&#39; => &#39;value3&#39;,
);    $mem->setMulti($items);    $res = $mem->get(&#39;key1&#39;);//value

    //返回系统常量
    var_dump($mem->getOption(Memcached::OPT_COMPRESSION));    //返回最后一次操作的结果描述消息
    $mem->add(&#39;a&#39;, &#39;bar&#39;); // first time should succeed
    echo $mem->getResultMessage(), "\n"; //SUCCESS

    //查看此key在哪个服务器上
    $mem->add(&#39;a&#39;, &#39;bar&#39;); // first time should succeed
    $res = $mem->getServerByKey(&#39;a&#39;);    //array(3) { ["host"]=> string(9) "127.0.0.1" ["port"]=> int(11211) ["weight"]=> int(0) } 

    //返回服务器列表
    var_dump($mem->getServerList());    //返回服务器状态
    var_dump($mem->getServerList());    //服务器版本
    print_r($mem->getVersion());    //判断是否是持久链接
    $res = $mem->isPersistent();    //Memcached::replace()和Memcached::set()类似,但是如果 服务端不存在key, 操作将失败。
    $m->set(&#39;hh&#39;, &#39;aaaa&#39;);    $m->replace(&#39;hh&#39;, &#39;bbbb&#39;);    $res = $m->get(&#39;hh&#39;);    //删除从已知的服务器列表中的所有缓存服务器,重置回空。
    $mem->resetServerList();    //对某一key重新设置生命周期
    $m->set(&#39;aaaa&#39;, &#39;aaaa&#39;, 600);    $m->touch(&#39;aaaa&#39;, 5);    $value= $m->get(&#39;aaaa&#39;);    //关闭打开的链接
    $m->quit();

    var_dump($value);
Copy after login
Copy after login

The following suffix is ​​ByKey, which is generally used by multiple Memcached Servers. If you master the above commands, you will basically use them below.

touch->touchByKey
setMulti->setMultiByKey
getMulti->getMultiBykey
replace->replaceByKey
append->appendByKey
prepend->prependByKey
getServerByKey
getdelay->getDelayedByKey 
increment->incrementByKey
decrement->decrementByKey
add->addByKey
get->getByKey
delete->deleteMultiByKey
Copy after login
Copy after login
$m->addByKey(&#39;指定服务器&#39;,&#39;键&#39;,"值")
Copy after login
Copy after login

Related recommendations:

How to install Memcached service method in linux

Ubuntu memcached installation and configuration method in php

PHP memory caching function memcached example

The above is the detailed content of How to use Memcached commands in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles