Home>Article>PHP Framework> A brief analysis of handling interface concurrency in Laravel

A brief analysis of handling interface concurrency in Laravel

藏色散人
藏色散人 forward
2021-02-13 09:20:49 3799browse

The following tutorial column ofLaravelwill introduce you to the simple processing of interface concurrency in Laravel. I hope it will be helpful to friends in need!

Simple handling of interface concurrency in Laravel

Introduction

Concurrent processing of interfaces often occurs in daily business logic. The most common is that the same interface is adjusted several times instantly, resulting in confusing data.
In order to avoid this problem, generally front-end and mobile terminals There will be restrictions on button triggering interface restrictions and backend interface call restrictions.

Said before

This method is only suitable for simple interface frequency limitation. It does not apply to product flash sales, but the principle is similar.

Principle

This is just a simple implementation process. It mainly uses the redis native set method class to set the expiration time when setting the value of the key. If the changed key exists, return false. If it does not exist, set the value and set the expiration time, and return true. The occurrence of deadlock is avoided.

Code part:

/** * 简单处理并发 * @User yaokai * @param $key 要设置的key * @param int $ttl 限制过期时间 * @param int $value 要设置的值 * @return bool true成功 false失败 */ function redisConcurren($key, $ttl = 240, $value = 1) { // 实例化原生 redis $redis = new \Redis(); // 指定需要使用的 redis 服务器 $redis->connect(config('database.redis.default.host')); // 设置密码 $redis->auth(config('database.redis.default.password')); // 设置默认的 redis 库 $redis->select(config('database.redis.default.database')); // 利用原生的set方法设置一个key的过期时间 $status = $redis->set($key, $value, array( 'nx', 'ex' => $ttl )); return $status; }

Written at the back

I am just a newbie who is learning slowly. If there is something wrong or there is a better way, I hope you will give me your advice and discuss with each other. Thank you very much!

The above is the detailed content of A brief analysis of handling interface concurrency in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete