PHP随笔二之nosql缓存类

3 篇文章 0 订阅
1 篇文章 0 订阅
== 简介 ==
 memcache : 是一套分布式的高速缓存系统。可用于提升网站的访问速度,对网站访问速度提升效果非常明显。
 
 reids    : redis是一个高性能的key-value数据库。支持的value类型较于memcache会更多。

== 两者的不同 ==
存储方式
 memcache  : 会把数据全存在内存当中,当然断电之后会挂掉,存储数据不能超过内存大小。
 redis     : 既可以把数据存在内存当中,也可以将数据转移到硬盘当中,可以保持数据的持久化。

数据格式
 memcache : 可以存储字符串,数组,图片,文件。
 redis    : 存储类型较于memcache会更多,包括string,list,set,zset,hash

运用场景
 memcache : 如果只是key-value简单的数据存储的话,memcache完全可以胜任,效果也不错,内存使用率更高一点。所以我们一般应用程序的话,用memcache的话
 完全是可以的。
 redis    : 如果对持久化需求或者对数据结构和处理有高级要求的话,可以考虑选择redis。

总结
 无论是memcache还是redis,性能方面都比较优秀,所以没必要过多的关注性能。两者各有各自的长处,在两者的选择上,我个人理解是,根据具体应用去
 选择。memcache比较简单粗暴,如果只是单纯的key-value操作的话, memcache会是个不错的选择,它已经足够可靠安全了,而且,memcache较于redis的内存使
 用率会更高一点。如果需要不只是GET/SET操作的时候而是更多复杂操作的时候,选择redis会更好。

== 查看服务器上的memcache和redis ==
 执行命令查看 ps -aux | grep memcache 和 ps -aux | grep redis
 redis可直接输入命令redis进入操作。

== 使用方式 ==
 经过一番折腾,总算把memcacahe和redis集成为一个较为完整的类
 该类的使用方法可以调用cache基类,也可以直接调用相关类进行使用。

 cache基类 :
 使用方式 : $cacher = Business_CacheHelper_Cache::getInstance('redis');
            $cacher->set('hang', 'zhou', 100);
            $cacher->get('hang');

 memcache类 :
 使用方式 : $memcacheObj = new Business_CacheHelper_Memcache();
              $memcacheObj->set('hang', 'zhou');
              $memcacheObj->get('hang');

 redis类 :
 使用方式 : $redisObj= new Business_CacheHelper_Memcache();
            $redisObj->set('hang', 'zhou');
            $redisObj->get('hang');

 == 代码清单 ==
 Cache类 :
 
<?php
 class Business_CacheHelper_Cache
 {
     /**
      * 缓存连接参数
      * @var string
      * @access protected
      */
     protected $_options = array();
     
     /**
      * 缓存对象
      * @var object
      * @access proteced
      */
     protected $_cacher;
     
     /**
      * 链接缓存
      * @param  string  $type 连接类型
      * @param  array   $options 连接参数
      * @return $object
      */
     public function connect($type = '', $options = array())
     {
          $cache = null;
          $type = empty($type) ? 'memcache' : $type;
          $class = 'Business_CacheHelper_' . ucwords(strtolower($type));
          if (class_exists($class)) {
               $cache = new $class($options);
          } else {
               echo '未找到缓存基类';
          }
          return $cache;
     }
     
     /**
      * 获取实例化对象
      * @param string $type
      * @param array $options
      * @return  mixed
      */
     static function getInstance($type = '', $options = array())
     {
          static $_instance = array();
          $uniqueId = json_encode($options);
          if (!isset($_instance[$uniqueId])) {
               $cacher = new self();
               $_instance[$uniqueId] = $cacher->connect($type, $options);
          }
          return $_instance[$uniqueId];
     }
     
     public function __get($name)
     {
          return $this->get($name);
     }
     
     public function __set($name, $value)
     {
          return $this->set($name, $value);
     }
     
     public function __remove($name)
     {
          return $this->remove($name);
     }
     
     public function setOptions($name, $value)
     {
          $this->_options[$name] = $value;
     }
     
     public function getOptions($name = '')
     {
          if (!empty($name)) {
               return $this->_options[$name];
          } else {
               return $this->_options;
          }         
     }
 }

 == memcache ==
 
<?php
 /**
 * memcache缓存助手类
 * @author 应杲臻<yinggaozhen@myhexin.com>
 * @create on 2015年10月28日 13:00
 */
 class Business_CacheHelper_Memcache extends Business_CacheHelper_Cache
 {
     public function __construct($options = array())
     {
          if (!extension_loaded('memcache')) {
               echo "未安装memcache\n";
          }
          $defaultOption = array(
               'host'       => '127.0.0.1',
               'port'       => '11211',
               'timeout'    => false,
               'persistent' => false
          );
          $options = array_merge($defaultOption, $options);
          $this->options    =    $options;
          $this->options['expire'] = isset($options['expire']) ? $options['expire'] : 3600;
          $this->options['prefix'] = isset($options['prefix']) ? $options['prefix'] : '';
          $func = $options['persistent'] ? 'pconnect' : 'connect';
          $this->cacher = new Memcache();
          $options['timeout'] === false ?
               $this->cacher->$func($options['host'], $options['port']) :
               $this->cacher->$func($options['host'], $options['port'], $options['timeout']);
     }
     
     /**
      * 读取缓存
      * @access public
      * @param string $name
      * @return mixed
      */
     public function get($name)
     {
          $value = $this->cacher->get($this->options['prefix'] . $name);
          $jsonDta = json_decode($value, true);  
          return $jsonDta === NULL ? $value : $jsonDta;
     }
     
     /**
      * 设置缓存
      * @access public
      * @param string $name 缓存键值
      * @param mixed  $value 缓存值
      * @param integer $expire 缓存有效期(秒) 如果为0的话则表示永久,但是最多不超过30天
      * @return boolean
      * @tips:
      * 存储类型只能为数字和字符串,数组存储需序列化
      */
     public function set($name, $value, $expire = null)
     {
          $expire = is_null($expire) ? $this->options['expire'] : $expire;
          $name = $this->options['prefix'] . $name;
          $value = (is_array($value) || is_object($value)) ? json_encode($value) : $value;
          return $this->cacher->set($name, $value, 0, $expire);
     }
     
     /**
      * 替换缓存
      * @access public
      * @param string $name 缓存键值
      * @param mixed  $value 缓存值
      * @param integer $expire 缓存有效期(秒) 如果为0的话则表示永久,但是最多不超过30天
      * @return boolean
      * @tips:此行为同设置缓存,唯一不同的是如果检测没有替换的key值,会返回false
      */
     public function replace($name, $value, $expire = null)
     {
          $expire = is_null($expire) ? $this->options['expire'] : $expire;
          $name = $this->options['prefix'] . $name;
          return $this->cacher->replace($name, $value, 0, $expire);
     }
     
     /**
      * 删除缓存
      * @access public
      * @param string $name 待删除缓存名
      * @return boolean
      */
     public function remove($name)
     {
          $name = $this->options['prefix'] . $name;
          return $this->cacher->delete($name);
     }
     
     /**
      * @access public
      * @return boolean
      * 清空缓存
      */
     public function clear()
     {
          return $this->cacher->flush();
     }
 }

  == redis ==
 
<?php
 /**
 * redis缓存助手类
 * @author 应杲臻<yinggaozhen@myhexin.com>
 * @create on 2015年10月28日 13:00
 */
 class Business_CacheHelper_Redis extends Business_CacheHelper_Cache
 {
     public function __construct($options = array())
     {
          if (!extension_loaded('redis')) {
               echo "未安装redis\n";
          }
          $defaultOption = array(
               'host'       => '127.0.0.1',
               'port'       => 6379,
               'timeout'    => false,
               'persistent' => false
          );
          $options = array_merge($defaultOption, $options);
          $this->options    =    $options;
          $this->options['expire'] = isset($options['expire']) ? $options['expire'] : 3600;
          $this->options['prefix'] = isset($options['prefix']) ? $options['prefix'] : '';
          $func = $options['persistent'] ? 'pconnect' : 'connect';
          $this->cacher = new Redis();
          $options['timeout'] === false ?
               $this->cacher->$func($options['host'], $options['port']) :
               $this->cacher->$func($options['host'], $options['port'], $options['timeout']);
     }
     
     /**
      * 读取缓存
      * @access public
      * @param string $name
      * @return mixed
      */
     public function get($name)
     {
          return $this->cacher->get($this->options['prefix'] . $name);
     }
     
     /**
      * 设置缓存
      * @access public
      * @param string $name 缓存键值
      * @param mixed  $value 缓存值
      * @param integer $expire 缓存有效期(秒) 如果为0的话则表示永久,但是最多不超过30天
      * @return boolean
      * @tips:
      * 存储类型只能为数字和字符串,数组存储需序列化
      */
     public function set($name, $value, $expire = null)
     {
          $expire = is_null($expire) ? $this->options['expire'] : $expire;
          $name = $this->options['prefix'] . $name;
          if (is_int($expire) && $expire > 0) {
               $result = $this->cacher->setex($name, $expire, $value);
          } else {
               $result = $this->cacher->set($name, $value);
          }
          return $result;
     }
     
     /**
      * 判断是否存在该键值
      * @access public
      * @param string $name 键值
      * @return boolean
      */
     public function exists($name)
     {
          $name = $this->options['prefix'] . $name;
          return $this->cacher->exists($name);
     }
     
     /**
      * 获取生存周期
      * @access public
      * @param string $name 键值
      * @return integer $ttl 剩余生存周期  
      * @tips :
      * ttl返回值有三种返回值,分别是-1|0|>0 ,代表永久|不存在|剩余生命周期事件
      */
     public function ttl($name)
     {
          if (!$this->exists($name)) {
               return 0;
          } else {
               $name = $this->options['prefix'] . $name;
               return $this->cacher->ttl($name);
          }
     }
     
     /**
      * 删除缓存
      * @access public
      * @param string $name 待删除缓存名
      * @return boolean
      */
     public function remove($name)
     {
          $name = $this->options['prefix'] . $name;
          return $this->cacher->delete($name);
     }
     
     /**
      * 清空缓存
      * @access public
      * @return boolean
      */
     public function clear()
     {
          return $this->cacher->flushDB();
     }
 }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值