Home > PHP Framework > Laravel > body text

A brief analysis of handling interface concurrency in Laravel

藏色散人
Release: 2021-02-13 09:20:49
forward
3835 people have browsed it

The following tutorial column of Laravel will 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;
}
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!