当前位置: 移动技术网 > IT编程>开发语言>PHP > Redis在Laravel项目中的应用实例详解

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

前言

本文主要给大家介绍了关于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 命令

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网