Redis在Laravel项目中的应用实例详解
https://mp.weixin.qq.com/s/axIgNPZLJDh9VFGVk7oYYA
在初步了解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' =>
];
});
定义帖子的访问路由
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: %;
height: %;
}
*{
margin: ;
border: ;
}
.jumbotron{
margin-top: %;
}
.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 = ; /**
* 同一用户浏览同一个帖子的过期时间
*/
const ipExpireSec = ; /**
* 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, ]);
//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, '']);
}
}
}
Redis在Laravel项目中的应用实例详解的更多相关文章
- Maven项目中的pom.xml详解【转】
什么是pom? pom作为项目对象模型.通过xml表示maven项目,使用pom.xml来实现.主要描述了项目:包括配置文件:开发者需要遵循的规则,缺陷管理系统,组织和licenses,项目的url, ...
- Laravel框架中的make方法详解
为什么网上已经有这么多的介绍Laravel的执行流程了,Laravel的容器详解了,Laravel的特性了,Laravel的启动过程了之类的文章,我还要来再分享呢? 因为,每个人的思维方式和方向是不一 ...
- 项目中如何使用babel6详解
由于浏览器的版本和兼容性问题,很多es6,es7的新的方法都不能使用,等到可以使用的时候,可能已经过去了很多年.Babel可以把es6,es7的新代码编译成兼容绝大多数的主流浏览器的代码. 本篇文章主 ...
- Vue项目三、项目中碰到的问题详解
一.组件的划分创建 方法一: 把页面上需要复用的模块,拆分成组件.比如,页面的header.footer.面包屑.弹出框等拆分成组件.所以在src中应该有一个文件夹(components)专门放这些会 ...
- 【转】C#中Serializable序列化实例详解
这篇文章主要介绍了C#中Serializable序列化,以实例形式详细讲述了系列化的技术及各种序列化方法,非常具有实用价值,需要的朋友可以参考下 本文实例讲述了C#中Serializable序列化.分 ...
- BI项目中的ETL设计详解(数据抽取、清洗与转换 )(转载)
原文:http://www.cnblogs.com/reportmis/p/5939732.html ETL是BI项目最重要的一个环节,通常情况下ETL会花掉整个项目的1/3的时间,ETL设计的好坏直 ...
- javascript中ajax post实例详解
一,原生态的XMLHttpRequest 代码如下 复制代码 <script language="javascript"> function savei ...
- C# 中的EventHandler实例详解-转
//这里定义了一个水箱类 public class 水箱 { //这是水箱的放水操作 public void 放水() { } //这是水箱的属性 public double 体积; ...
- Linux备份数据库,mysqldump命令实例详解
mysqldump是mysql数据库中备份工具,用于将MYSQL服务器中的数据库以标准的sql语言的方式导出,并保存到文件中. 语法: mysqldump (选项) 选项: --add-drop-ta ...
随机推荐
- linux实时系统监控工具mpstat
mpstat (RHEL5默认不安装) mpstat是MultiProcessor Statistics的缩写,是实时系统监控工具.其报告与CPU的一些统计信息,这些信息存放在/proc/stat文件 ...
- RQNOJ PID141 / 寻找代表元 [2017年6月计划 二分图01]
PID141 / 寻找代表元 ☆ 提交你的代码 查看讨论和题解 1分前 我的状态 已通过 2017-06-28 21:03:46 运行耗时:31 ms 运行内存:28048 KB 查看最后一次评测记录 ...
- Leetcode24.Swap Nodes in Pairs两两交换链表中的节点
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表. 示例: 给定 1->2->3->4, 你应该返回 2->1->4->3. 说明: 你的算法只能使用常数的 ...
- python通过http(multipart/form-data)上传文件的方法
之前写过一篇博客,说的如何python如何通过http下载文件,今天写一篇博客来介绍如下,python如何通过request库实现上传文件 这里主要是解决multipart/form-data这种格式 ...
- 数据挖掘案例:基于 ReliefF和K-means算法的应用
数据挖掘案例:基于 ReliefF和K-means算法的应用 数据挖掘方法的提出,让人们有能力最终认识数据的真正价值,即蕴藏在数据中的信息和知识.数据挖掘(DataMiriing),指的是从大型数据库 ...
- 【Pyqt5】自定义信号简单原理(易懂版),多窗口交互,传输数据,调用方法
PS:如果你想在2窗口调用1窗口的内部方法,或者在2窗口传递数据给1窗口数据,本片博客可以放心食用 主窗口: class MainWindow(QWidget,Ui_MainFrom): insert ...
- Codeforces Round #263 (Div. 2) A. Appleman and Easy Task【地图型搜索/判断一个点四周‘o’的个数的奇偶】
A. Appleman and Easy Task time limit per test 1 second memory limit per test 256 megabytes input sta ...
- PHP队列类
/** * Created by PhpStorm. * User: LAMP-Q哥 * Date: 2017/8/3 * Time: 12:58 */ class Queue { private $ ...
- Tool-图片压缩-腾讯智图:腾讯智图
ylbtech-Tool-图片压缩-腾讯智图:腾讯智图 智图是腾讯ISUX前端团队开发的一个专门用于图片压缩和图片格式转换的平台,其功能包括针对png,jpeg,gif等各类格式图片的压缩,以及为上传 ...
- cocos2dX 之CCAnimation/CCAnimate
我们今天来学习cocos2dX里面的动画的制作, 有人说, 不是前面CCAction已经学过了吗? 怎么还要学, CCAction是动作, 而我们今天要学的是动画哦, 是让一个东西动起来哦, 好了进入 ...