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


Posted in PHP onAugust 11, 2017

前言

本文主要给大家介绍了关于Redis在Laravel项目中的应用实例,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍:

在初步了解Redis在Laravel中的应用 那么我们试想这样的一个应用场景 一个文章或者帖子的浏览次数的统计 如果只是每次增加一个浏览量

就到数据库新增一个数据 如果请求来那个太大这对数据库的消耗也就不言而喻了吧 那我们是不是可以有其他的解决方案

这里的解决方案就是 即使你的网站的请求量很大 那么每次增加一个访问量就在缓存中去进行更改 至于刷新Mysql数据库可以自定义为

多少分钟进行刷新一次或者访问量达到一定数量再去刷新数据库 这样数据也是准确的 效率也比直接每次刷新数据库要高出许多了

既然给出了相应的解决方案 我们就开始实施

我们以一篇帖子的浏览为例 我们先去创建对应的控制器

$ php artisan make:controller PostController

再去生成需要用到的 Model

$ php artisan make:model Post -m

填写posts的迁移表的字段内容

Schema::create('posts', function (Blueprint $table) {
 $table->increments('id');
 $table->string("title");
 $table->string("content");
 $table->integer('view_count')->unsigned();
 $table->timestamps();
});

还有就是我们测试的数据的Seeder填充数据

$factory->define(App\Post::class, function (Faker\Generator $faker) {
 return [
 'title' => $faker->sentence,
 'content' => $faker->paragraph,
 'view_count' => 0
 ];
});

定义帖子的访问路由

Route::get('/post/{id}', 'PostController@showPost');

当然我们还是需要去写我们访问也就是浏览事件的(在app/providers/EventServiceProvider中定义)

protected $listen = [
 'App\Events\PostViewEvent' => [
//  'App\Listeners\EventListener',
  'App\Listeners\PostEventListener',
 ],
 ];

执行事件生成监听

$ php artisan event:generate

之前定义了相关的路由方法 现在去实现一下:

public function showPost(Request $request,$id)
{
 //Redis缓存中没有该post,则从数据库中取值,并存入Redis中,该键值key='post:cache'.$id生命时间5分钟
 $post = Cache::remember('post:cache:'.$id, $this->cacheExpires, function () use ($id) {
 return Post::whereId($id)->first();
 });

 //获取客户端请求的IP
 $ip = $request->ip();
 
 //触发浏览次数统计时间
 event(new PostViewEvent($post, $ip));

 return view('posts.show', compact('post'));
}

这里看的出来就是以Redis作为缓存驱动 同样的 会获取获取的ip目的是防止同一个ip多次刷新来增加浏览量

同样的每次浏览会触发我们之前定义的事件 传入我们的post和id参数

Redis的key的命名以:分割 这样可以理解为一个层级目录 在可视化工具里就可以看的很明显了

接下来就是给出我们的posts.show的视图文件

<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>
 <!-- 新 Bootstrap 核心 CSS 文件 -->
 <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="external nofollow" >
 <style>
 html,body{
  width: 100%;
  height: 100%;
 }
 *{
  margin: 0;
  border: 0;
 }
 .jumbotron{
  margin-top: 10%;
 }
 .jumbotron>span{
  margin: 10px;
 }
 </style>
</head>
<body>
<div 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}} views</span>
  <p>Content:{{$post->content}}</p>
  </div>
 </div>
 </div>
</div>

<!-- jQuery文件-->
<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>

</script>
</body>
</html>

初始化我们的事件就是接收一下这些参数即可

class PostViewEvent
{
 use Dispatchable, InteractsWithSockets, SerializesModels;

 public $ip;
 public $post;


 /**
 * PostViewEvent constructor.
 * @param Post $post
 * @param $ip
 */
 public function __construct(Post $post, $ip)
 {
 $this->post = $post;
 $this->ip = $ip;
 }

 /**
 * Get the channels the event should broadcast on.
 *
 * @return Channel|array
 */
 public function broadcastOn()
 {
 return new PrivateChannel('channel-name');
 }
}

最主要的还是编写我们的监听事件:

class PostEventListener
{
 /**
 * 一个帖子的最大访问数
 */
 const postViewLimit = 20;

 /**
 * 同一用户浏览同一个帖子的过期时间
 */
 const ipExpireSec = 200;

 /**
 * Create the event listener.
 *
 */
 public function __construct()
 {

 }


 /**
 * @param PostViewEvent $event
 */
 public function handle(PostViewEvent $event)
 {
 $post = $event->post;
 $ip = $event->ip;
 $id = $post->id;
 //首先判断下ipExpireSec = 200秒时间内,同一IP访问多次,仅仅作为1次访问量
 if($this->ipViewLimit($id, $ip)){
  //一个IP在300秒时间内访问第一次时,刷新下该篇post的浏览量
  $this->updateCacheViewCount($id, $ip);
 }
 }

 /**
 * 限制同一IP一段时间内得访问,防止增加无效浏览次数
 * @param $id
 * @param $ip
 * @return bool
 */
 public function ipViewLimit($id, $ip)
 {
 $ipPostViewKey = 'post:ip:limit:'.$id;
 //Redis命令SISMEMBER检查集合类型Set中有没有该键,Set集合类型中值都是唯一
 $existsInRedisSet = Redis::command('SISMEMBER', [$ipPostViewKey, $ip]);
 //如果集合中不存在这个建 那么新建一个并设置过期时间
 if(!$existsInRedisSet){
  //SADD,集合类型指令,向ipPostViewKey键中加一个值ip
  Redis::command('SADD', [$ipPostViewKey, $ip]);
  //并给该键设置生命时间,这里设置300秒,300秒后同一IP访问就当做是新的浏览量了
  Redis::command('EXPIRE', [$ipPostViewKey, self::ipExpireSec]);
  return true;
 }
 return false;
 }

 /**
 * 达到要求更新数据库的浏览量
 * @param $id
 * @param $count
 */
 public function updateModelViewCount($id, $count)
 {
 //访问量达到300,再进行一次SQL更新
 $post = Post::find($id);
 $post->view_count += $count;
 $post->save();
 }

 /**
 * 不同用户访问,更新缓存中浏览次数
 * @param $id
 * @param $ip
 */
 public function updateCacheViewCount($id, $ip)
 {
 $cacheKey = 'post:view:'.$id;
 //这里以Redis哈希类型存储键,就和数组类似,$cacheKey就类似数组名 如果这个key存在
 if(Redis::command('HEXISTS', [$cacheKey, $ip])){
  //哈希类型指令HINCRBY,就是给$cacheKey[$ip]加上一个值,这里一次访问就是1
  $save_count = Redis::command('HINCRBY', [$cacheKey, $ip, 1]);
  //redis中这个存储浏览量的值达到30后,就去刷新一次数据库
  if($save_count == self::postViewLimit){
  $this->updateModelViewCount($id, $save_count);
  //本篇post,redis中浏览量刷进MySQL后,就把该篇post的浏览量清空,重新开始计数
  Redis::command('HDEL', [$cacheKey, $ip]);
  Redis::command('DEL', ['laravel:post:cache:'.$id]);
  }
 }else{
  //哈希类型指令HSET,和数组类似,就像$cacheKey[$ip] = 1;
  Redis::command('HSET', [$cacheKey, $ip, '1']);
 }
 }
}

最后可以通过我们的工具查看具体效果

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对三水点靠木的支持。

相关链接

PHP 相关文章推荐
在任意字符集下正常显示网页的方法一
Apr 01 PHP
smarty中先strip_tags过滤html标签后truncate截取文章运用
Oct 25 PHP
php 操作符与控制结构
Mar 07 PHP
PHP APC配置文件2套和参数详解
Jun 11 PHP
php实现的短网址算法分享
Jun 20 PHP
php实现阿拉伯数字和罗马数字相互转换的方法
Apr 17 PHP
php实现购物车功能(上)
Jul 23 PHP
CodeIgniter辅助之第三方类库third_party用法分析
Jan 20 PHP
Zend Framework入门应用实例详解
Dec 11 PHP
超强多功能php绿色集成环境详解
Jan 25 PHP
thinkphp5.0自定义验证规则使用方法
Nov 16 PHP
PHP实现微信提现(企业付款到零钱)
Aug 01 PHP
PHP验证码无法显示的原因及解决办法
Aug 11 #PHP
php readfile()修改文件上传大小设置
Aug 11 #PHP
浅谈Laravel中的一个后期静态绑定
Aug 11 #PHP
浅谈PHP中new self()和new static()的区别
Aug 11 #PHP
php使用 readfile() 函数设置文件大小大小的方法
Aug 11 #PHP
详解PHP使用日期时间处理器Carbon人性化显示时间
Aug 10 #PHP
PHP弱类型语言中类型判断操作实例详解
Aug 10 #PHP
You might like
php获取mysql版本的几种方法小结
2008/03/25 PHP
php array_flip() 删除数组重复元素
2009/01/14 PHP
php读取mysql中文数据出现乱码的解决方法
2013/08/16 PHP
PHP使用xmllint命令处理xml与html的方法
2014/12/15 PHP
JavaScript效率调优经验
2009/06/04 Javascript
jQuery 学习 几种常用方法
2009/06/11 Javascript
浅谈Javascript鼠标和滚轮事件
2012/06/27 Javascript
jQuery实现鼠标悬停显示提示信息窗口的方法
2015/04/30 Javascript
使用JS批量选中功能实现更改数据库中的status状态值(批量展示)
2016/11/22 Javascript
JavaScript基于扩展String实现替换字符串中index处字符的方法
2017/06/13 Javascript
JS SetInterval 代码实现页面轮询
2017/08/11 Javascript
微信开发之企业付款到银行卡接口开发的示例代码
2018/09/18 Javascript
小程序实现列表多个批量倒计时
2021/01/29 Javascript
vue实现设置载入动画和初始化页面动画效果
2019/10/28 Javascript
js实现星星海特效的示例
2020/09/28 Javascript
基于Vue.js+Nuxt开发自定义弹出层组件
2020/10/09 Javascript
原生js+canvas实现验证码
2020/11/29 Javascript
vue 数据操作相关总结
2020/12/17 Vue.js
[01:07:13]TNC vs Pain 2018国际邀请赛小组赛BO2 第一场 8.17
2018/08/20 DOTA
详解Django中的过滤器
2015/07/16 Python
python中string模块各属性以及函数的用法介绍
2016/05/30 Python
Win10下Python3.7.3安装教程图解
2019/07/08 Python
对Pytorch神经网络初始化kaiming分布详解
2019/08/18 Python
python动态视频下载器的实现方法
2019/09/16 Python
详解python中groupby函数通俗易懂
2020/05/14 Python
Python Spyder 调出缩进对齐线的操作
2021/02/26 Python
7款设计巧妙的css3飘带状3D立体效果的导航菜单和表单窗口
2013/02/04 HTML / CSS
日本乐天官方海外转运服务:Rakuten Global Express
2018/11/30 全球购物
荷兰的时尚市场:To Be Dressed
2019/05/06 全球购物
德国婴儿服装和婴儿用品购买网站:Baby Sweets
2019/12/08 全球购物
毕业生求职简历的自我评价
2013/10/23 职场文书
2015年公共机构节能宣传周活动总结
2015/03/26 职场文书
一个独生女的故事观后感
2015/06/04 职场文书
八月迷情观后感
2015/06/11 职场文书
2019客服个人年终工作总结范文
2019/07/08 职场文书
Win11绿屏怎么办?Win11绿屏死机的解决方法
2021/11/21 数码科技