Examples of Redis's practical application in the Laravel project

Source: Internet
Author: User
This article mainly introduces about the application of Redis in the Laravel project, in the article through the sample code introduced in very detailed, for everyone to learn or use Laravel has a certain reference learning value, the need for friends to follow the small series to learn together.

Objective

This article mainly introduces to you about the Redis in the Laravel Project application example, shares out for everybody reference study, below words not to say, comes together to see the detailed introduction:

A preliminary understanding of the application of Redis in Laravel so let's just think of a scenario where an article or a post's number of views is counted if only one view is added each time

Just add a new data to the database if it's too big for the request, it's self-evident that the database is being consumed. So, can we have other solutions?

The solution here is that even if your site requests a large amount of traffic, you can make changes in the cache every time you add a visit to the refresh MySQL database is customizable to

How many minutes to refresh or to reach a certain number of times to refresh the database so the data is also more accurate and more efficient than the direct refresh of the database every time much higher

Now that we have the solution, we start to implement it.

Let's take a look at a post as an example, we'll first create the corresponding controller.


$ php Artisan Make:controller Postcontroller

To create the Model that needs to be used.


$ php Artisan Make:model post-m

Fill in the field contents of the Posts Migration table


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

And then there's the Seeder fill data for the data we're testing.


$factory->define (App\post::class, function (Faker\generator $faker) {return [' title ' = = $faker->sentence, ' Content ' = $faker->paragraph, ' View_count ' + 0];});

Define access routes for posts


Route::get ('/post/{id} ', ' postcontroller@showpost ');

Of course we still need to write our visit, which is the browse event (defined in App/providers/eventserviceprovider)


protected $listen = [' app\events\postviewevent ' = [//  ' App\listeners\eventlistener ',  ' app\listeners\ Posteventlistener ',],];

Perform event generation monitoring


$ PHP Artisan event:generate

The relevant routing method has been defined before now to implement:


Public Function Showpost (Request $request, $id) {//redis cache does not have the post, the value is taken from the database and stored in Redis, the key value key= ' Post:cache '. $ ID life time 5 minutes $post = Cache::remember (' Post:cache: '. $id, $this->cacheexpires, function () use ($id) {return Post::whereid ($id)->first (); }); Gets the IP $ip of the client request = $request->ip ();  Trigger View Count Time event (new Postviewevent ($post, $ip)); Return view (' Posts.show ', compact (' post '));

What we see here is that Redis is the cache driver. The same IP is acquired to prevent multiple refreshes of the same IP to increase the number of views

The same time each visit triggers our post and ID parameters that were previously defined by the event we passed in

The name of the Redis key is: Split this can be understood as a hierarchical directory in the visualization tool can be seen clearly

The next step is to give our posts.show view file.


Initializing our event is to receive these parameters


Class postviewevent{use dispatchable, Interactswithsockets, serializesmodels, public $ip; public $post;/** * Postvieweve NT 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 ');}}

The main thing is to write our listener events:


Class posteventlistener{/** * Maximum number of visits for a post */const POSTVIEWLIMIT = 20;/** * The same user browses the expiration time of the same post */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; First judge the next ipexpiresec = 200 seconds time, the same IP access multiple times, only as 1 traffic if ($this->ipviewlimit ($id, $ip)) {//An IP in 300 seconds to access the first time, Refresh the number of views on this post $this->updatecacheviewcount ($id, $IP); }}/** * Restricts access to the same IP over time, preventing an increase in invalid views * @param $id * @param $ip * @return BOOL */Public Function ipviewlimit ($id, $ip) {$i Ppostviewkey = ' post:ip:limit: '. $id; The Redis command Sismember checks that the collection type set has no such key, the values in the Set collection type are unique $existsInRedisSet = Redis::command (' Sismember ', [$ipPostViewKey, $ IP]); If this build does not exist in the collection then create a new one and set the expiration time if (! $existsInRedisSet) {//sadd, set type directive, add a value to the Ippostviewkey key to the IP redis::command (' Sadd ', [$  Ippostviewkey, $ip]); And give the key to set the life time, here set 300 seconds, 300 seconds after the same IP access as a new PageView Redis::command (' EXPIRE ', [$ipPostviewkey, self::ipexpiresec]); return true; } return false; }/** * Up to the required update database views * @param $id * @param $count */Public Function Updatemodelviewcount ($id, $count) {//traffic reached 300, then once SQL Update $post = post::find ($id); $post->view_count + = $count; $post->save (); }/** * Different user access, update cache browse times * @param $id * @param $ip */Public Function Updatecacheviewcount ($id, $ip) {$cacheKey = ' post:v Iew: '. $id; Here, the keys are stored in the Redis hash type, similar to arrays, $cacheKey similar to the array name if the key exists if (Redis::command (' hexists ', [$cacheKey, $ip])) {//hash type directive Hincrby  is to give $cachekey[$ip] plus a value, where one visit is 1 $save _count = Redis::command (' Hincrby ', [$cacheKey, $ip, 1]); When the value of this storage view in Redis reaches 30, it refreshes the database if ($save _count = = self::p ostviewlimit) {$this->updatemodelviewcount ($id, $save _  count);  After the Post,redis in this article is brushed into MySQL, the amount of the post is emptied and the count is restarted Redis::command (' Hdel ', [$cacheKey, $ip]);  Redis::command (' DEL ', [' Laravel:post:cache: '. $id]);  }}else{//hash type directive Hset, and array similar, like $cachekey[$ip] = 1; Redis::command (' Hset ', [$cacheKey, $ip, ' 1 ']); } }}

Finally, we can see the effect through our tools.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.