一聚教程网:一个值得你收藏的教程网站

热门教程

laravel框架缓存使用配置与例子

时间:2022-06-25 00:46:55 编辑:袖梨 来源:一聚教程网

基础介绍

假设您的应用程序显示了十个最流行的歌曲提供给用户投票评选. 你真的需要在用户每次访问时否访问这十首歌曲吗?如果你可以存储10分钟的歌曲, 甚至一个小时以便大大加快您的应用程序, 该怎么办?使用 laravel缓存会变得非常简单.

laravel提供五个缓存的驱动模式:

•文件系统
数据库
•Memcached
•APC
•Redis
•内存 (Arrays)

默认情况下, Laravel被配置为使用文件系统缓存驱动, 这是不需要配置的. 文件系统驱动把缓存项作为文件存储在storage/cache目录.如果你满意这个驱动, 没有其他的配置是必需的. 直接使用它就好:

提示: 使用文件系统缓存驱动程序之前, 要确保你的storage/cache目录是可写的.


数据库

数据库缓存使用给定的简单的键值存储数据库表.使用之前, 首先在application/config/cache.php文件中设置数据库表的名称:

1.'database' => array('table' => 'laravel_cache'),下一步, 创建数据库表. 该表应具有三个列:

•key (varchar)
•value (text)
•expiration (integer)
就是这样. 一旦您的配置和表的设置设置好, 开始使用缓存吧!


Memcached
Memcached 是超快速, 维基百科和Facebook等网站都在使用的开源分布式内存对象缓存系统. 使用Laravel的Memcached的驱动程序之前, 您将需要安装和配置memcached和PHP的memcache扩展你的服务器上.

一旦Memcached在服务器上安装, 你必须在application/config/cache.php文件上设置驱动程序:

1.'driver' => 'memcached'然后, 添加您的memcached服务器到servers数组


Redis
Redis 是一个开源, 先进的键值存储库. 它通常被称为一个数据结构的服务器, 因为键可以包含的字符串(string), 哈希值(hashes), lists, sets, 和被排序的 sets.

在使用Redis的缓存驱动程序之前, 先设置Redis服务器. 在application/config/cache.php文件上设置驱动程序:

1.'driver' => 'redis'
缓存键值
为了避免与其他应用程序使用的APC, Redis或者memcached命名冲突, Laravel预先准备了一个key属性作为使用这些驱动的前缀, 可以随意更改此值:

1.'key' => 'laravel'
内存(In-Memory)缓存

"memory"缓存驱动实际上并不在磁盘缓存任何内容. 它只不过是维持当前请求的缓存数据的内部数组. 这使得在任何缓存机制完善前进行单元测试. 它不应该被用来作为一个"真正的(real)"缓存驱动.


其实从某种意义来说session也是一种缓存技术,为什么这么说,请看下下面分析。
laravel的缓存支持一下驱动”file”, “database”, “apc”, “memcached”, “redis”, “array”,其他的都不说,这里主要说下memcached和redis,

laravel框架你会发现他没有支持memcache缓存,而是memcached缓存,为什么,其实memcached缓存是memcache的一个升级版,相比而言,加入了一个锁的机制,详细可以去问百度。关于memcached的缓存配置,在cache.php文件中可以找到。

这里说下redis,在cache.php中是找不到redis的配置项的,那么在哪里呢?他在databases.php文件中个,laravel把它当作一种DB来配置的。

同样的session,如果你的驱动选择redis的话,他的配置同样的也是在这里选择。

下面是我的配置代码:

$redisCache = App::make('cache'); // Assumes "redis" set as your cache
$redisCache->setConnection('cache'); // Your redis cache connection
$redisCache->put('testtCacheIndex', 'fbbinValue', 10000);

13.),这里不得不说的一个问题在配置以redis为驱动的缓存服务还是session服务,我们都只能使用default这个配置项目,而不能指定特有的配置项,比如我想给我cache配置cache这个key指定的服务器,session也制定其他的,但是,laravel不支持酱紫(可能是我还不知道怎么弄,如果有大牛晓得了,请赐教,谢谢),那么我们要想我们的缓存服务器用我们指定的cache索引所指定的服务该怎么办呢?我们可以试试laravel的IOC,如下:

方案1:

$redis = Redis::connection('cache');
$redis->set('fbbin', 'fbbinValue');
var_dump($redis->get('fbbin'))

例子,使用Caching缓存数据减轻数据库查询压力 .

 闲话少说,开始吧,先说说我的具体需求:
    
     一.  实现首页的数据缓存,如果有没过期的缓存,就不查数据库,这样基本模拟出静态页的效果(当然了,其实还是要经过php处理的)

     二.  实现刷新指定缓存的功能(这里只有首页,就单指刷新首页缓存了,这个功能,我做到了admin模块下

     具体实现:
  
     一. 查阅文档,找到能帮我实现需求的模块

     我查了一下文档,发现了有Caching这样一个模块,顾名思义,就是缓存了,那它能否帮到我呢,看看先:

     1. http://laravel.com/docs/cache/config  这里是laravel的Caching模块的实现

     2. 文档中有如下描述:
   The Basics     Imagine your application displays the ten most popular songs as voted on by your users. Do you really need to look up these ten songs every time someone visits your site? What if you could store them for 10 minutes, or even an hour, allowing you to dramatically speed up your application? Laravel's caching makes it simple.
    
     我简单理解为:
    
     假设你的应用展示了用户投票最多的10首流行歌曲,你真的需要在每个人访问你的网站的时候都去查一遍这10首歌吗?如果你想按10分钟或者是一小时的频率来缓存查询结果来加速你的应用,Laravel 的 caching缓存模块能将使工作变得异常简单.

     嗯,从这段话,我已经了解到这完全符合我现在的需求了,接下来我只需要找到对应的使用方法和API,一步一步来就行了.

 

     二.  学习相应API等

     1. 还是上面文档,里面接着向下看,有如下描述:
      By default, Laravel is configured to use the file system cache driver. It's ready to go out of the box with no configuration. The file system driver stores cached items as files in the cache directory. If you're satisfied with this driver, no other configuration is required. You're ready to start using it.
     
     我简单理解为:

     默认情况下,Laravel使用文件系统作为缓存的驱动, 这是不需配置就可使用的, 文件系统驱动会将缓存的数据存入缓存目录下的文件里面去, 如果你觉得合适的话不需要做任何其他的配置直接开始用就行了.

     当然了, 这也是符合我的想法的, 其实我就是想把页面缓存成静态页文件, 用户再次访问时直接输出缓存的静态页就ok了, 如果需要更高级的需求, 还可以使用其他的驱动,有数据库驱动, memcached, redis驱动等, 很好很强大!

     2. 接下来查看用例,找到使用方法
    
     用例文档在这: http://laravel.com/docs/cache/usage

     可以看出, 里面有 get, put, forever, remember, has, forget 等方法,这些方法使用也是基本上能 "望文生义" 就能搞定的,呵呵
具体使用方法文档里面已经说的够详细, 使用方法一目了然我就不细说了, 只在代码里面说吧

 

      三. 具体实现
     
      1. 我首页之前的代码

class Home_Controller extends Base_Controller {

 public function get_index() {
  $posts = Post::with('user')
     ->join('users', 'users.id', '=', 'posts.post_author')
      -> order_by('posts.created_at', 'desc')
       ->get(array('posts.id', 'posts.support', 'posts.against', 'users.username', 'posts.post_author', 'posts.post_title', 'posts.post_body'));

  $data = array();

  foreach($posts as $p){
   $data[] = array(
    'id'      => $p -> id,
    'support' => $p -> support,
    'against' => $p -> against,
    'username'=> $p -> username,
    'post_author' => $p -> post_author,
    'post_title'  => $p -> post_title,
    'post_body'   => $p -> post_body
   );
  }

  return View::make('home.index')
    -> with('posts', $data);
 }

}
    这是我首页的controller,作用只有一个, 就是从博文表里面取得所有博文, 然后输出, 每次有人访问, 都要查表, 如果没有发表新的博文, 也要查表, 的确有很多不必要的开销


      2.  下面是我改装之后的代码:

class Home_Controller extends Base_Controller {

 public function get_index() {

  // 添加静态缓存支持
  // 如果不存在静态页缓存就立即缓存
  if ( !Cache::has('staticPageCache_home') ) {
   $data = array();

   $posts = Post::with('user')
      ->join('users', 'users.id', '=', 'posts.post_author')
       -> order_by('posts.created_at', 'desc')
        ->get(array('posts.id', 'posts.support', 'posts.against', 'users.username', 'posts.post_author', 'posts.post_title', 'posts.post_body'));

   foreach($posts as $p){
    $data[] = array(
     'id'      => $p -> id,
     'support' => $p -> support,
     'against' => $p -> against,
     'username'=> $p -> username,
     'post_author' => $p -> post_author,
     'post_title'  => $p -> post_title,
     'post_body'   => $p -> post_body
    );
   }

   $res = View::make('home.index')
    -> with('posts', $data);

   Cache::forever('staticPageCache_home', $res);
  }

  // 返回缓存的数据
  return Cache::get('staticPageCache_home');
 }

}

      这里我用到了三个api
     1). Cache::has ,这个判断是说如果当前不存在 staticPageCache_home 这个名字的缓存, 就立即去取数据

     2). Cache::forever,  这个从用例文档里面可知是"永久缓存"的意思, 因为我一般都是很勤劳的,如果发表了博文,自己再去后台立即刷新一下缓存就好了, 所以不需要设置过期啊失效时间之类的, 当然这个是要按各自的具体需求来的

     3). Cache::get , 这句是从缓存里面取出 staticPageCache_home 这个名字的缓存, 然后作为响应内容返回

     嗯, 就这么简单, 呵呵, 一个基本的缓存功能就完成了, laravel的确是不错地!

     3. 为后台添加刷新缓存功能
     还是贴代码吧, 不过也很简单:

  public function get_refreshcache() {
    /*
        @var $GID admin组id
    */
    $GID = 1;

    if ( Auth::user() -> gid === 1 ) {

        $data = array();

        $posts = Post::with('user')
                ->join('users', 'users.id', '=', 'posts.post_author')
                -> order_by('posts.created_at', 'desc')
                ->get(array('posts.id', 'posts.support', 'posts.against', 'users.username', 'posts.post_author', 'posts.post_title', 'posts.post_body'));

        foreach($posts as $p){
            $data[] = array(
                'id'      => $p -> id,
                'support' => $p -> support,
                'against' => $p -> against,
                'username'=> $p -> username,
                'post_author' => $p -> post_author,
                'post_title'  => $p -> post_title,
                'post_body'   => $p -> post_body
            );
        }

        $res = View::make('home.index')
                -> with('posts', $data);

        Cache::forever('staticPageCache_home', $res);

        return '刷新首页缓存成功!';
    }

    return '对不起,只有管理员组才可进行此操作!';
}

       我给后台添加了一个项目, 对应这个方法, 方法内容和首页的大同小异, 取数据, 然后Cache::forever 刷新一下缓存,就这么简单,当然了,上面的Auth::user() 判断是个简单的判断,只有管理员组才能进行刷新操作,呵呵

热门栏目