PHP和Memcached - 在PHP中的应用 - Memcached类介绍 - 封装自己的Memcached类库

1、Memcached类的介绍

详见PHP官方文档:点击访问

2、封装自己的Memcached类库

<?php

namespace Cache\Lib;

class MemCache
{
/**
* @var \Memcached
* 访问变量可以使用Memcached类库的其他方法
*/
public $_memcache; public function __construct($persistentId = null)
{
$cache = new \Memcached($persistentId); //判断服务器地址是否为空
if(!$cache->getServerList())
{
//一般从config文件中读取服务器地址
//添加服务器地址,去掉s只能添加一个服务器地址
$cache->addServers(
array(
//ip地址,端口,权重 | 权重越大,该服务越容易被选中
array('192.168.3.105', 11211, 60),
array('192.168.3.105', 11311, 40),
)
);
} //key 前缀的设置
$cache->setOption(\Memcached::OPT_PREFIX_KEY, 'imooc.'); $this->_memcache = $cache;
} /**
* 设置缓存
* @param string $key 缓存key
* @param string|array $value
* @param int $ttl 过期时间
* @return bool
*/
public function set($key, $value, $ttl = 3600)
{
if(empty($key) || empty($value) || is_numeric($ttl))
{
return false;
} return $this->_memcache->set($key, $value, $_SERVER['REQUEST_TIME'] + $ttl);
} /**
* 获取缓存
* @param $key
* @return bool|mixed
*/
public function get($key)
{
if(empty($key))
{
return false;
}
return $this->_memcache->get($key);
} /**
* 清空缓存处理
* @param $key
* @return bool
*/
public function clean($key)
{
if(empty($key))
{
return false;
} return $this->_memcache->delete($key);
} /**
* 自增处理
* @param $key
* @param $offset
* @return bool|int
*/
public function incr($key, $offset = 1)
{
if(empty($key))
{
return false;
}
$offset = intval($offset);
return $this->_memcache->increment($key, $offset);
} /**
* 自减少处理
* @param $key
* @param int $offset
* @return bool|int
*/
public function decr($key, $offset = 1)
{
if(empty($key))
{
return false;
}
$offset = intval($offset);
return $this->_memcache->decrement($key, $offset);
} /**
* add处理
* @param $key
* @param $value
* @param int $ttl
* @return bool
*/
public function add($key, $value, $ttl = 3600)
{
if(empty($key) || empty($value) || is_numeric($ttl))
{
return false;
} return $this->_memcache->add($key, $value, $_SERVER['REQUEST_TIME'] + $ttl);
} }

如有错误之处,请纠正。谢谢!

上一篇:Android 关于apk 打包后的地图定位和导航失败的问题


下一篇:log4j.property配置