search
HomeBackend DevelopmentPHP TutorialLaravel uses Caching to cache data to reduce database query pressure, laravelcaching_PHP tutorial

Laravel uses Caching to cache data to reduce database query pressure, laravelcaching

This article describes the example of Laravel using Caching to cache data to reduce database query pressure. Share it with everyone for your reference, the details are as follows:

Yesterday I wanted to cache the homepage of my blog to achieve an effect similar to generating a static page cache. I asked everyone in the group how to cache, but they were all very busy and didn’t reply much, so I went to read the documentation myself. , I discovered the Caching part. In fact, I had an impression of it before, but I had no specific contact with it. As the name suggests, it is caching. It must be somewhat related to my needs. I took a closer look and found that it was indeed too powerful. The process was very simple. In a few steps, I modified the homepage, tested it with firebug, and improved the parsing time by dozens of milliseconds. Of course, some people will laugh at whether this is necessary. Isn’t it a pain in the ass? In fact, I think it is necessary. Yes, it’s just that there are not many visitors here (actually no one visits at all, hehe...), and secondly, the queries I do on the homepage are quite few so far, just once, which is to get all the blog posts. If a page There are seven or eight or even more than ten queries in it. I think the effect should be obvious! (Of course, Brother Raymond also mentioned using a more advanced dedicated cache to do it (memcached and the like), this This can only be achieved if you have control over the server and can freely install software or if the server already has these caching mechanisms. My needs are relatively simple and I don’t have the environment to do it, so I won’t consider it here)

Without further ado, let’s get started and talk about my specific needs:

1. Implement data caching on the home page. If there is a cache that has not expired, the database will not be checked. This basically simulates the effect of a static page (of course, it still needs to be processed by PHP)

2. Implement the function of refreshing the specified cache (there is only the home page here, so it only means refreshing the home page cache. I have implemented this function under the admin module

Detailed implementation:

1. Check the documentation and find the module that can help me achieve my needs

I checked the documentation and found out that there is a module called Caching. As the name suggests, it is caching. So if it can help me, let’s see first:

1. http://laravel.com/docs/cache/config Here is the implementation of laravel’s Caching module

2. The document has the following description:

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 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.

I simply understand it as:

Suppose your app displays the 10 most popular songs voted by users, do you really need to check these 10 songs every time everyone visits your website? If you want to click 10 minutes or one To cache query results every hour to speed up your application, Laravel's caching module can make the job extremely easy.

Well, from this paragraph, I have learned that this completely meets my current needs. Next, I just need to find the corresponding usage methods and APIs, step by step.

2. Learn the corresponding API, etc.

1. Still in the above document, look down and see the following description:

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.

I simply understand it as:

By default, Laravel uses the file system as the cache driver, which can be used without configuration. The file system driver will store the cached data in the file in the cache directory. If you think it is appropriate, do not If you need to do any other configuration, just start using it.

Of course, this is also in line with my idea. In fact, I just want to cache the page into a static page file. When the user visits again, it will be ok to directly output the cached static page. If you need more advanced requirements, you can also use Other drivers include database drivers, memcached, redis drivers, etc., which are very good and powerful!

2. Next, check the use cases and find out how to use it

The use case documentation is here: http://laravel.com/docs/cache/usage

As you can see, there are methods such as get, put, forever, remember, has, forget, etc. These methods can basically be used "literally", haha

The specific usage documentation has already been explained in detail. I won’t go into details since the usage is clear at a glance. I’ll just explain it in the code

3. Specific implementation

1. The code before my homepage

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);
  }
}

This is the controller on my homepage. It has only one function, which is to get all the blog posts from the blog post table and then output it. Every time someone visits, the table must be checked. If no new blog post is published, the table must be checked. Indeed, there is. A lot of unnecessary expenses

2. The following is the code after my modification:

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() 判断是个简单的判断,只有管理员组才能进行刷新操作,呵呵

嗯, 全部内容就这么多, 很简单, 欢迎童鞋们拍砖指正!

希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。

您可能感兴趣的文章:

  • Laravel框架中实现使用阿里云ACE缓存服务
  • Laravel中扩展Memcached缓存驱动实现使用阿里云OCS缓存
  • 基于laravel制作APP接口(API)
  • PHP框架Laravel学习心得体会
  • 使用AngularJS和PHP的Laravel实现单页评论的方法
  • PHP IDE PHPStorm配置支持友好Laravel代码提示方法
  • Laravel 5 框架入门(四)完结篇
  • Laravel 5 框架入门(三)
  • Laravel 5 框架入门(二)构建 Pages 的管理功能
  • Laravel 5 框架入门(一)
  • Laravel 5框架学习之用户认证
  • Laravel 5框架学习之Eloquent 关系
  • Laravel 5框架学习之子视图和表单复用
  • Laravel 5框架学习之表单验证
  • Laravel 5框架学习之日期,Mutator 和 Scope

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1110070.htmlTechArticleLaravel使用Caching缓存数据减轻数据库查询压力的方法,laravelcaching 本文实例讲述了Laravel使用Caching缓存数据减轻数据库查询压力的方法。分享...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
laravel单点登录方法详解laravel单点登录方法详解Jun 15, 2022 am 11:45 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于单点登录的相关问题,单点登录是指在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统,下面一起来看一下,希望对大家有帮助。

一起来聊聊Laravel的生命周期一起来聊聊Laravel的生命周期Apr 25, 2022 pm 12:04 PM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于Laravel的生命周期相关问题,Laravel 的生命周期从public\index.php开始,从public\index.php结束,希望对大家有帮助。

laravel中guard是什么laravel中guard是什么Jun 02, 2022 pm 05:54 PM

在laravel中,guard是一个用于用户认证的插件;guard的作用就是处理认证判断每一个请求,从数据库中读取数据和用户输入的对比,调用是否登录过或者允许通过的,并且Guard能非常灵活的构建一套自己的认证体系。

laravel中asset()方法怎么用laravel中asset()方法怎么用Jun 02, 2022 pm 04:55 PM

laravel中asset()方法的用法:1、用于引入静态文件,语法为“src="{{asset(‘需要引入的文件路径’)}}"”;2、用于给当前请求的scheme前端资源生成一个url,语法为“$url = asset('前端资源')”。

实例详解laravel使用中间件记录用户请求日志实例详解laravel使用中间件记录用户请求日志Apr 26, 2022 am 11:53 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于使用中间件记录用户请求日志的相关问题,包括了创建中间件、注册中间件、记录用户访问等等内容,下面一起来看一下,希望对大家有帮助。

laravel中间件基础详解laravel中间件基础详解May 18, 2022 am 11:46 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于中间件的相关问题,包括了什么是中间件、自定义中间件等等,中间件为过滤进入应用的 HTTP 请求提供了一套便利的机制,下面一起来看一下,希望对大家有帮助。

laravel的fill方法怎么用laravel的fill方法怎么用Jun 06, 2022 pm 03:33 PM

在laravel中,fill方法是一个给Eloquent实例赋值属性的方法,该方法可以理解为用于过滤前端传输过来的与模型中对应的多余字段;当调用该方法时,会先去检测当前Model的状态,根据fillable数组的设置,Model会处于不同的状态。

laravel路由文件在哪个目录里laravel路由文件在哪个目录里Apr 28, 2022 pm 01:07 PM

laravel路由文件在“routes”目录里。Laravel中所有的路由文件定义在routes目录下,它里面的内容会自动被框架加载;该目录下默认有四个路由文件用于给不同的入口使用:web.php、api.php、console.php等。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)