php实现基于shmop扩展的数据缓存

http://eslizn.com/post/php-data-cache-for-shmop.html

今天上课时研究了下PHP的数据缓存,根据网上的资料,一般采用serialize序列化存储,读取时将数据通过unserialize将数据反序列化还原.

接着,缓存一般存储在文件或者内存中.在大型应用中,一般是将模板缓存和数据缓存分割开来的,而且是将模板缓存以文件的形式缓存,数据使用内存来缓存.这样的架构能在很大程度上减轻数据库和程序的压力.

关于php操作内存,我选择了shmop扩展,其方法只有6个:

  • shmop_open 打开内存块.
  • shmop_write 向内存块中写入数据
  • shmop_size 获得内存块大小
  • shmop_read 读取内存块数据
  • shmop_delete 删除内存块数据
  • shmop_close 关闭内存块
 
打开内存块使用shmop_open 成功返回shmid,失败返回false:
1
int shmop_open ( int $key , string $flags , int $mode , int $size )
参数$key是用来标识共享内存段的,一般使用ftok函数生成.
参数$flags是内存段属性:
  • a:只读内存段
  • c:读写内存段,如果内存段不存在则创建
  • w:读写内存段
  • n:创建一个新的内存段,如果已经存在则返回失败.
参数$mode是内存段访问权限,采用八进制数据,如0664
参数$size是内存段大小.
向内存段中写入数据shmop_write 成功返回写入数据大小,失败返回false:
1
int shmop_write ( int $shmid , string $data , int $offset )
参数$shmid是使用shmop_open返回的一个id.
参数$data是要写入的数据.
参数$offset是写入数据的偏移量.
从内存段中读取数据使用shmop_read 成功返回数据,失败返回false
1
string shmop_read ( int $shmid , int $start , int $count )
参数$shmid是使用shmop_open返回的一个id.
参数$start是要读取数据在内存段中的起始位置.
参数$count是要读取的数据长度.
获取内存段的数据大小使用shmop_size 返回数据长度
1
int shmop_size ( int $shmid )
参数$shmid是使用shmop_open返回的一个id.
删除内存段使用shmop_delete 成功返回true,失败返回false
1
bool shmop_delete ( int $shmid )
参数$shmid是使用shmop_open返回的一个id.
关闭内存段使用shmop_close
1
void shmop_close ( int $shmid )
参数$shmid是使用shmop_open返回的一个id.
 
/*
 *  Memcache 内存缓存模块
 *          init()          初始化
 *      get($key)       获取数据
 *      set($key,$val)      存储数据
 *      del($key)       删除数据
 *      close()         关闭内存段
 *  Author Eslizn http://eslizn.com  at 2011-12-17
*/
 
class Memcache
{
    public static $list=array();
 
    public static function init()
    {
        //Memcache::close();
    }
 
    public static function get($key)
    {
        if(isset(Memcache::$list[$key]))
        {
            return unserialize(shmop_read(Memcache::$list[$key],0,shmop_size(Memcache::$list[$key])));
        }
        return false;
    }
 
    public static function set($key,$val)
    {
        $val=serialize($val);
        if(isset(Memcache::$list[$key]))
        {
            shmop_close(Memcache::$list[$key]);
        }
        Memcache::$list[$key] = shmop_open(ftok(__FILE__, $key),"c",0664,strlen($val));
        shmop_write(Memcache::$list[$key],$val,0);
        return true;
    }
 
    public static function del($key)
    {
        if(isset(Memcache::$list[$key]))
        {
            return shmop_delete(Memcache::$list[$key]);
        }
    }
 
    public static function close()
    {
        while(!empty(Memcache::$list))
        {
            shmop_close(array_pop(Memcache::$list));
        }
        return true;
    }
}
posted @ 2012-03-31 13:17  luckc#  阅读(641)  评论(0)    收藏  举报