本文实例讲述了Laravel使用Caching缓存数据减轻数据库查询压力的方法。分享给大家供大家参考,具体如下:
昨天想把自己博客的首页做一下缓存,达到类似于生成静态页缓存的效果,在群里问了大家怎么做缓存,都挺忙的没多少回复,我就自己去看了看文档,发现了Caching这个部分,其实之前也有印象,但是没具体接触过,顾名思义,就是缓存了,那肯定和我的需求有点联系,我就认真看了看,发现的确是太强大了,经过很简单的几个步骤,我就改装好了首页,用firebug测试了一下,提高了几十毫秒解析时间,当然了有人会笑这有必要吗,岂不是闲的蛋疼?其实我想这是有必要的,只是在我这里一来访问人少(其实根本没人还,嘿嘿....),二来我在首页里做的查询目前还挺少,就一次,就是取得所有博文,如果一个页面里面有个七八次乃至十多次查询,我想这个效果应该就很明显了吧!(当然了,Raymond哥还有提到用更高级的专用缓存去做(memcached之类吧貌似),这是要自己能取得服务器控制权,能自由安装软件或者服务器本来就有这些缓存机制的情况下才能实现的,我需求比较简单,也没有这个环境去做,所以这里就不考虑了)
闲话少说,开始吧,先说说我的具体需求:
一. 实现首页的数据缓存,如果有没过期的缓存,就不查数据库,这样基本模拟出静态页的效果(当然了,其实还是要经过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() 判断是个简单的判断,只有管理员组才能进行刷新操作,呵呵
嗯, 全部内容就这么多, 很简单, 欢迎童鞋们拍砖指正!
更多关于Laravel相关内容感兴趣的读者可查看本站专题:《Laravel框架入门与进阶教程》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.