宝哥软件园

Redis在Laravel项目中的应用实例详解

编辑:宝哥软件园 来源:互联网 时间:2021-09-04

本文主要介绍Redis在Laravel项目中的应用实例,并分享给大家参考。下面的话就不多说了,我们来看看详细的介绍:

在初步了解了Redis在Laravel中的应用后,让我们设想这样一个应用场景。如果文章或帖子的浏览量统计一次只增加一个页面浏览量,

只需向数据库中添加一个新数据。如果要求太大,就不言而喻了。我们能有其他解决方案吗

这里的解决方案是,即使您的网站有大量的请求,您也可以在每次增加访问次数时在缓存中进行更改。至于刷新Mysql数据库,可以自定义为

刷新多少分钟,或者一定次数的访问刷新数据库,这样数据准确,效率比每次直接刷新数据库高很多

现在我们已经给出了相应的解决方案,我们将开始实施它

让我们以浏览帖子为例。让我们首先创建相应的控制器

$ PHP工匠制作:控制器后控制器,以生成所需的模型

$ PHP artisan make :模型post-m填充了帖子迁移表的字段内容

schema : create(' post '),function(蓝图$ table){ $ table-increments(' id ');$ table-string(' title ');$ table-string(' content ');$ table-整数(' view _ count ')-无符号();$ table-时间戳();});还有我们测试的数据的播种机填充数据

$ factory-define(App post : CLaSS,function(Faker Generator $ Faker){ return[' title '=$ Faker-句子,' content '=$ Faker-段落,' view _ count '=0];});定义帖子的访问路径

Route:get('/post/{id} ','[email protected]');当然,我们仍然需要写我们的访问,即浏览事件(在app/providers/event serviceprovider中定义)

受保护的$ listen=[' App Events post view event '=[///' App listener event listener ',' App Listeners PostEventListener ',],];执行事件生成侦听

$ php artisan event:generate之前定义了相关的路由方法。现在实行:

Public函数show post (request $ request,$ id){//如果Redis缓存中没有post,则从数据库中获取该值并将其存储在Redis中。该键值为key='post:cache '。$id生存期为5分钟$ post=cache:记住(' post3360cache 3360 '。$ id,$ this-cache expires,function()use($ id){ return post 3360:其中id($)});//获取客户端请求的IP $ IP=$ request-IP();//触发浏览次数统计时间事件(新增postviewevent ($ post,$ IP));返回视图(' posts.show ',compact(' post '));}这里可以看到的是,使用Redis作为缓存驱动,将获得相同的ip。目的是防止同一ip被多次刷新以增加页面浏览量

同样的浏览会触发我们之前定义的事件,传递到我们的帖子和id参数中

Redis键的名称除以:可以理解为一个分层目录,在可视化工具中可以看得很清楚

下一步是给出我们帖子的视图文件

html lang=' en ' head meta charset=' utf-8 ' meta http-equiv=' X-UA-Compatible ' content=' IE=edge ' meta name=' viewport ' content=' width=device-width,initial-scale=1 ' title bootstrap Template/title!-新引导程序核心半铸钢钢性铸铁(铸造半钢)文件- link rel='样式表href='//cdn。bootscs。com/bootstrap/3。3 .5/CSS/bootstrap。量滴CSS ' rel='外部' nofollow '样式html,正文{宽度: 100%;高度: 100%;} * { margin : 0;边框: 0;} .jumbo tron { margin-top : 10%;} .jumbotronspan { margin : 10px }/style/head dydiv class=' container ' div class=' row ' div class=' col-xs-12 col-MD-12 ' div class=' jumbotron ' h1 title : { { $ post-title } }/h1 span class=' glyphicon glyphicon-eye-open ' aria-hidden=' true ' { $ post-view _ count } } view/span pcontent : { $ post-content } }/p- jQuery文件-脚本src=' http://cdn。bootcss。com/jquery/1。11 .3/jquery。量滴js '/脚本!-最新的引导程序核心Java脚本语言文件-脚本src=' http://cdn。bootscs。com/bootstrap/3。3 .5/js/自举。量滴js '/脚本脚本/脚本/正文/html初始化我们的事件就是接收一下这些参数即可

类PostViewEvent{使用可调度、交互带套接字、序列化模型公共$ ip公共$ post/** * PostViewEvent构造函数* @ param Post $ Post * @ param $ IP */public function _ _ construct(Post $ Post,$ IP){ $ this-Post=$ Post;$ this-IP=$ IP;} /** *获取事件应该广播的频道。* * @返回通道|阵列*/公共函数broadcastOn(){ 0返回新的专用频道(“频道名称”);}}最主要的还是编写我们的监听事件:

Class PostEventListener{ /** *一篇帖子的最大访问次数*/const PostViewLimit=20;/* * *同一用户浏览同一帖子的过期时间*/const ipExpireSec=200;/** *创建事件侦听器。* */public function _ _ construct(){ }/* * * @ param PostView event $ event */public function handle(PostView event $ event){ $ post=$ event-post;$ IP=$ event-IP;$ id=$ post-id;//首先判断ipExpireSec=200秒,同一个IP被多次访问,仅视为一次访问if($ this-ipviewclimit($ ID,$ IP)){//300秒内第一次访问一个IP时,下一篇帖子的页面浏览量刷新为$ this-updatecacheviewcount ($ ID, $ IP) }}/* * *在一段时间内限制对同一IP的访问,以防止无效浏览次数的增加* @ param $ id * @ param $ IP * @ return bool */public function ipview limit($ id,$ IP){ $ ippostviewkey=' post 3360 IP 3360 limit 3360 '。 $ id//Redis命令SISMEMBER检查该键是否存在于Set类型中,Set集合类型中的值是唯一的$ existsinrediset=Redis :3360 command(' SISMEMBER ',[$ ippostviewkey,$ IP]);//如果集合中不存在此建筑,请创建一个新建筑,并设置到期时间if(!$ existsinrediset){//SADD,集合类型指令,给ipPostViewKey添加一个值ipredis:3360command ('sadd ',[$ ipPostViewKey,$ IP];//并设置此键的使用寿命,为300秒。300秒后,相同的IP访问将被视为新的页面视图。Redis:3360command ('expire ',[$ ippostviewkey,self 33603360 ipexpiresec]);返回真;}返回false}/* * *更新数据库所需的页面浏览量* @ param $ id * @ param $ count */public函数updatemodelviewcount ($ id,$ count){//当页面浏览量达到300时,再次更新SQL $ $ post=post : find($ id);$ post-view _ count=$ count;$ post-save();}/* * *不同用户访问、更新缓存中的浏览次数* @ param $ id * @ param $ IP */public函数updatecacheviewcount ($ id,$ IP){ $ cachekey=' post 3360 view 3360 '。$ id//这里的键存储为Redis哈希类型,类似于array,$cacheKey类似于array name。如果这个键有if(redis : command(' h ' exists,[$ cachekey,$ IP]){//hash类型指令HINCRBY,就是给$cacheKey[$ip]加一个值。这里的一次访问是1 $ save _ count=redis :3360 command(' hinc rby ',[$ cachekey,$ IP,1]);//一旦//redis中的这个内存页号的值达到30,if($ save _ count==self :3360 postviewlimit){ $ this-updatemodelviewcount($ id,$ save _ count)刷新数据库;//本文和Redis的页面浏览量刷入MySQL后,清除本文的页面浏览量,重新开始计数Redis:3360 Command ('hdel ',[$ cachekey,$ IP]);Redis:command('DEL ',[' laravel : post : cache : '。$ id]);} }else{ //hash类型指令HSET,类似于array,就像$ cacheKey[$ IP]=1;Redis:command('HSET ',[$cacheKey,$ip,' 1 ']);}}}最后,我们可以通过我们的工具检查具体效果

摘要

以上就是本文的全部内容。希望本文的内容能给你的学习或工作带来一些帮助。有问题可以留言交流。谢谢你的支持。

相关链接

Redis命令

更多资讯
游戏推荐
更多+