memcached 第3章 PHP与memcached memcached 第3章 PHP与memcached

2018-10-23

1、安装扩展

①、PHP扩展 memcache 与 memcached 的区别

PHP操作memcached服务有两个扩展 memcache 和 memcached。

  • memcache扩展支持面向对象和面向过程两种接口。它的函数受php.ini影响,所以必须在php.ini配置文件中设置。该扩展出现时间较早(2004年)。PHP Memcache 扩展包下载地址

  • memcached 扩展使用了libmemcached库提供的api与memcached服务端进行交互。 所以安装时需要先安装libmemcached库。 memcached扩展只支持面向对象的接口。 安装时不需要在php.ini中配置,只引入 extension即可。 该扩展出现时间较晚(2009年)。 memcached功能比memcache更全,支持的函数更多。PHP Memcached 扩展包下载地址

推荐使用memcached扩展。memcached功能更全一点。

②、linux 安装 php-memcache(记得看扩展包是否支持你的PHP版本)

cd usr/local/src
wget http://pecl.php.net/get/memcache-3.0.8.tgz
tar -zxvf memcache-3.0.8.tgz
cd memcache-3.0.8
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make && make install

打开你的php.ini文件在最后添加以下内容

extension = memcache.so

通过浏览器访问 phpinfo() 函数,查看是否有 memcache 扩展

③、linux 安装 php-memcached(记得看扩展包是否支持你的PHP版本)

A、安装 libmemcached

cd /usr/local/src
wget http://pecl.php.net/get/memcache-3.0.8.tgz
tar -zxvf libmemcached-1.0.18.tar.gz
cd libmemcached-1.0.18
./configure --prefix=/usr/local/libmemcached --with-memcached
make && make install

B、安装 php-memcached

cd usr/local/src
wget http://pecl.php.net/get/memcached-3.0.4.tgz#这是php7的 
tar -zxvf memcached-3.0.4.tgz
cd memcached-3.0.4
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config --with-libmemcached-dir=/usr/local/libmemcached
make && make install

C、打开你的php.ini文件在最后添加以下内容

echo "extension=memcached.so" >> /etc/php.ini #/etc/php.ini为php.ini路径
extension = memcached.so

D、添加完后重新启动 php-fpm

pkill php-fpm
/usr/local/php/sbin/php-fpm

E、检查安装结果

/usr/local/php/bin/php -m | grep memcached

安装成功会输出:memcached。

或者通过浏览器访问 phpinfo() 函数

https://file.lulublog.cn/images/3/2022/08/olURSjFPNlu5lru51lupRRPLl1ZRnu.png

问题集锦:

A、如果编译过程中

WARNING: You will need re2c 0.13.4 or later

解决

yum -y install re2c

B、如果yum安装的php报错:checking for zlib location... configure: error: memcached support requires ZLIB.

解决方法:

yum -y install zlib-devel

C、configure: error: no, sasl.h is not available. Run configure with --disable-memcached-sasl to disable this check

解决方法:在配置选项中加入--disable-memcached-sasl这功能比较诡异而且没用,禁用它

D、Centos 下使用 yum 命令快速安装 Memcached 与 php-memcached:

rpm qa|grep memcached //首先检查memcache是否已经安装完成
yum install  memcached //(提示你是否确认安装输入y)检查完成后执行安装命令
yum install  php-memcached //安装php的memcache的扩展
systemctl start httpd //开启apache
systemctl start memcached //开启memcached
setenforce

E、这些函数的行为受 php.ini 中的设置影响。

  • memcached.sess_locking integer 开启session支持。有效值: On, Off, 默认值 On.

  • memcached.sess_consistent_hash integer Memcached 是否使用一致性哈希保存session。如果为On,session数据保存则使用一致性哈希模式。 使用一致性哈希,可以保证你在增加或删除memcached服务器节点的时候不会导致session大规模的失效。 默认此项是关闭的。

  • memcached.sess_binary integer Memcached session是否使用二进制模式。如果Libmemcached 开启二进制模式。默认值是 Off.

  • memcached.sess_lock_wait integer Session 自旋锁等待时间(微秒)。请小心设置此值。值的类型是整数,当此值被设置为0的时候,lock wait的时间将会使用系统默认值,Memcached扩展中默认值是150000。

  • memcached.sess_prefix string 设置memcached session key的前缀。session前缀最长为219字节长的字符串。默认值是“memc.sess.key.”。

  • memcached.sess_number_of_replicas integer 使用memcached写session多少个副本。

  • memcached.sess_randomize_replica_read integer Memcached session 是否随机复制读。默认值0

  • memcached.sess_remove_failed integer 是否允许自动剔除出故障的memcached服务器。默认值0

  • memcached.compression_type string 设置memcached的压缩类型,允许的值为fastlz, zlib。默认值是fastlz(快速无损压缩,性能不错)。

  • memcached.compression_factor float 压缩因子. 保存时压缩因子超过设置的极限才会将数据压缩存储。存储压缩条件: plain_len > comp_len * factor。默认是1.3 (节省23%的空间)。

  • memcached.compression_threshold integer 压缩阈值。不压缩的序列化值低于此阈值。默认值是2000字节。

  • memcached.serializer string 设置缓存对象的默认序列化程序。有效值: php, igbinary, json, json_array.

2、PHP 操作 Memcached

官方文档

①、addServer、addServers、getserverbykey、getserverlist、setSaslAuthData、resetServerList

//向服务器池中增加一个服务器
public bool Memcached::addServer ( string $host , int $port [, int $weight = 0 ] )
//向服务器池中增加多台服务器
public bool Memcached::addServers ( array $servers )
//获取一个key所映射的服务器信息
public array Memcached::getServerByKey ( string $server_key )
//获取服务器池中的服务器列表
public array Memcached::getServerList ( void )
//设置用于身份验证的凭据
public void Memcached::setSaslAuthData ( string $username , string $password )
//清除服务器列表中的所有服务器
public bool Memcached::resetServerList ( void )
  • host:memcached服务端主机名。如果主机名无效,相关的数据操作的返回代码将被设置为Memcached::RES_HOST_LOOKUP_FAILURE。

  • port:memcached服务端端口号,通常是11211。

  • weight:此服务器相对于服务器池中所有服务器的权重。此参数用来控制服务器在操作时被选种的概率。这个仅用于一致性 分布选项,并且这个值通常是由服务端分配的内存来设置的。

addServer("mem1.domain.com", 11211, 33);
$m->addServer("mem2.domain.com", 11211, 67);

③、add、addByKey、getByKey

//向一个新的key下面增加一个元素
public bool Memcached::add ( string $key , mixed $value [, int $expiration ] )
//在指定服务器上的一个新的key下增加一个元素
public bool Memcached::addByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )
//从特定的服务器检索元素
public mixed Memcached::getByKey ( string $server_key , string $key [, callback $cache_cb [, float &$cas_token ]] )
addServer("127.0.0.1",11211);
if($m->add("mystr","this is a memcache test!",3600)){
    echo "原始数据缓存成功!";
}else{
    echo "数据已存在:".$m->get("mystr");
}

Memcached::getByKey()除了可以通过server_key参数自由的指定key 所映射的服务器外, 在功能上等同于Memcached::get()

  • $server_key也是一个普通的key, *ByKey系列接口的工作过程是: 首先, 对$server_key进行hash, 得到$server_key应该存储的服务器, 然后将相应的操作在 $server_key所在的服务器上进行。

  • cache_cb:通读缓存回掉函数或NULL.

  • cas_token:检索的元素的CAS标记值

④、append、appendByKey、replace、replaceByKey

//向已存在元素后追加数据
public bool Memcached::append ( string $key , string $value )
//向指定服务器上已存在元素后追加数据
public bool Memcached::appendByKey ( string $server_key , string $key , string $value )
//替换已存在key下的元素
public bool Memcached::replace ( string $key , mixed $value [, int $expiration ] )
//从指定服务器上替换已存在key下的元素
public bool Memcached::replaceByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )

⑤、cas、casByKey

//比较并交换值
public bool Memcached::cas ( float $cas_token , string $key , mixed $value [, int $expiration ] )
//在指定服务器上比较并交换值
public bool Memcached::casByKey ( float $cas_token , string $server_key , string $key , mixed $value [, int $expiration] )

⑥、decrement、decrementByKey、increment、incrementByKey

//减小数值元素的值
public int Memcached::decrement ( string $key [, int $offset = 1 ] )
//减少指定服务器上数值元素的值
public int Memcached::decrementByKey ( string $server_key , string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] )
//增加数值元素的值
public int Memcached::increment ( string $key [, int $offset = 1 ] )
//增加指定服务器上数值元素的值
public int Memcached::incrementByKey ( string $server_key , string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] )

⑦、delete、deletebykey、deleteMulti、deleteMultiByKey

//删除一个元素
public bool Memcached::delete ( string $key [, int $time = 0 ] ) //time 服务端等待删除该元素的总时间(或一个Unix时间戳表明的实际删除时间).
//从指定的服务器删除一个元素
public bool Memcached::deleteByKey ( string $server_key , string $key [, int $time = 0 ] )
//批量删除元素
public array Memcached::deleteMulti ( array $keys [, int $time = 0 ] )
//从指定的服务器批量删除元素
public bool Memcached::deleteMultiByKey ( string $server_key , array $keys [, int $time = 0 ] )

⑧、get、getByKey、getAllKeys、getMulti、getMultiByKey

//检索一个元素
public mixed Memcached::get ( string $key [, callback $cache_cb [, float &$cas_token ]] ) //ache_cb通读缓存回掉函数或NULL.
//从特定的服务器检索元素
public mixed Memcached::getByKey ( string $server_key , string $key [, callback $cache_cb [, float &$cas_token ]] )
//检索在所有服务器上的元素
public array Memcached::getAllKeys ( void )
//检索多个元素
public mixed Memcached::getMulti ( array $keys [, array &$cas_tokens [, int $flags ]] ) //如果提供了参数cas_tokens,对于检索到的元素会为其添加CAS标记值。
//从特定服务器检索多个元素
public array Memcached::getMultiByKey ( string $server_key , array $keys [, string &$cas_tokens [, int $flags ]] )

⑨、getDelayed、getDelayedByKey、fetch、fetchAll

//请求多个元素:向Memcached服务端发出一个检索keys指定的多个 key对应元素的请求。这个方法不会等待响应而是立即返回。
//当你需要收集元素值时, 调用Memcached::fetch()或 Memcached::fetchAll()。如果with_cas设置为true,会同时请求每个元素的CAS标记。
public bool Memcached::getDelayed ( array $keys [, bool $with_cas [, callback $value_cb ]] )
//从指定的服务器上请求多个元素
public bool Memcached::getDelayedByKey ( string $server_key , array $keys [, bool $with_cas [, callback $value_cb ]] )
//抓取下一个结果
public array Memcached::fetch ( void )
//抓取所有剩余的结果
public array Memcached::fetchAll ( void )
addServer("localhost", 11211);

$m->set("int", 99);
$m->set("string", "a simple string");
$m->set("array", array(11, 12));

$m->getDelayed(array("int", "array"), true);
var_dump($m->fetchAll());
addServer("localhost", 11211);

$m->set("int", 99);
$m->set("string", "a simple string");
$m->set("array", array(11, 12));

//延迟的获取int和array这两个key的值
$m->getDelayed(array("int", "array"), true);
//循环抓取上面的延迟抓取得到的结果
while ($result = $m->fetch()) {
    var_dump($result);
}

⑩、set、setByKey、setMulti、setMultiByKey、touch、touchByKey、

//存储一个元素
public bool Memcached::set ( string $key , mixed $value [, int $expiration ] ) //值可以是任何有效的非资源型php类型, 因为资源类型不能被序列化存储。如果Memcached::OPT_COMPRESSION 选项开启, 序列化的值同样会被压缩存储。
//在指定服务器上存储一个元素
public bool Memcached::setByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )
//存储多个元素
public bool Memcached::setMulti ( array $items [, int $expiration ] )
//在指定服务器上存储多个元素
public bool Memcached::setMultiByKey ( string $server_key , array $items [, int $expiration ] )
//设置元素的到期时间
public bool Memcached::touch ( string $key , int $expiration )
//在指定服务器上设置元素的到期时间
public bool Memcached::touchByKey ( string $server_key , string $key , int $expiration )
addServer("localhost", 11211);

$m->set("int", 99);
$m->set("string", "a simple string");
$m->set("array", array(11, 12));
/* "object"这个key将在5分钟后过期 */
$m->set("object", new stdclass, time() + 300);
addServer("localhost", 11211);

$items = array(
    "key1" => "value1",
    "key2" => "value2",
    "key3" => "value3"
);
$m->setMulti($items, time() + 300);

⑪、getResultCode、getResultMessage

//返回最后一次操作的结果代码
public int Memcached::getResultCode ( void )
//返回最后一次操作的结果描述消息
public string Memcached::getResultMessage ( void )
addServer("localhost", 11211);

$m->add("foo", "bar");
if ($m->getResultCode() == Memcached::RES_NOTSTORED) {
   
}

⑫、setOption、setOptions、getOption

//设置一个memcached选项
public bool Memcached::setOption ( int $option , mixed $value )
//批量设置memcached选项
public bool Memcached::setOptions ( array $options )
//获取Memcached的选项值
public mixed Memcached::getOption ( int $option )
getOption(Memcached::OPT_HASH) == Memcached::HASH_DEFAULT);
$m->setOption(Memcached::OPT_HASH, Memcached::HASH_MURMUR);
$m->setOption(Memcached::OPT_PREFIX_KEY, "widgets");
echo "Prefix key is now: ", $m->getOption(Memcached::OPT_PREFIX_KEY), "\n";
getOption(Memcached::OPT_HASH) == Memcached::HASH_DEFAULT);

$m->setOptions(array(Memcached::OPT_HASH => Memcached::HASH_MURMUR, Memcached::OPT_PREFIX_KEY => "widgets"));

var_dump($m->getOption(Memcached::OPT_HASH) == Memcached::HASH_DEFAULT);
echo "Prefix key is now: ", $m->getOption(Memcached::OPT_PREFIX_KEY), "\n";

⑬、flush、quit、isPristine、isPersistent、getStats、getVersion

//作废缓存中的所有元素
public bool Memcached::flush ([ int $delay = 0 ] )
//关闭所有打开的链接
public bool Memcached::quit ( void )
//检查实例是否已创建
public bool Memcached::isPristine ( void )
//检查实例是否正在使用
public bool Memcached::isPersistent ( void )
//获取服务器池的统计信息
public array Memcached::getStats ( void )
//获取服务器池中所有服务器的版本信息
public array Memcached::getVersion ( void )

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开微信扫一扫,即可进行扫码打赏哦

阅读 2970