PHP uses Redis locks to restrict concurrent access classes sample _php Tips

Source: Internet
Author: User
Tags auth redis reserved

This article introduces PHP using Redis lock to restrict concurrent access classes, and introduces the concurrency access restriction method in detail.

1. Concurrent access restriction issues

For scenarios where you need to restrict concurrent access for the same user, users can request success multiple times if the user concurrently requests multiple times and the server processing has no lock restrictions.

For example, if a coupon is exchanged at the same time, the user can exchange the coupon with the same replacement code in the absence of a lock restriction.

Pseudo code is as follows:

If A (you can change the collar)
B (Perform the redemption)
C (updated to replaced)
D (end)

If the user makes an exchange of the collar code, it can pass the judgement of (a) can be replaced (a), because there must be a change of the collar (B), will be updated to have been replaced (C). So if the user has a number of requests before an update has been swapped, these requests can be executed successfully.

2. Concurrent access restriction methods

Using file locks enables concurrent access restrictions, but using file locks does not guarantee concurrent access restrictions on multiple servers for a distributed schema environment.

Redis is an open source, with the use of ANSI C language, support network, can be based on memory can also be persistent log-type, Key-value database, and provide a variety of language APIs.

This article will use its Setnx method to implement the distributed lock function. SETNX is the set it N**ot ex**ists.

Insert succeeds when key value does not exist (get lock succeeded), insert fails if key value already exists (get lock failed)

RedisLock.class.PHP

<?php/** * Redis lock Operation class * date:2016-06-30 * author:fdipzone * ver:1.0 * * FUNC: * Public Lock acquire lock * public
  Unlock Release lock * Private Connect * * class Redislock {//class start Private $_config;

  Private $_redis; /** * Initialization * @param Array $config Redis Connection Set/Public function __construct ($config =array ()) {$this->_conf
    IG = $config;
  $this->_redis = $this->connect (); /** * Acquire lock * @param String $key Lock ID * @param Int $expire Lock Expiration * @return Boolean/Public functio

    n Lock ($key, $expire =5) {$is _lock = $this->_redis->setnx ($key, Time () + $expire);

      Cannot get lock if (! $is _lock) {//To determine whether the lock expires $lock _time = $this->_redis->get ($key);
        The lock is expired, the lock is removed, and the If (Time () > $lock _time) {$this->unlock ($key) is retrieved;
      $is _lock = $this->_redis->setnx ($key, Time () + $expire); } return $is _lock?
  True:false; /** * Release lock * @param String $key Lock Identification * @returnBoolean/Public Function unlock ($key) {return $this->_redis->del ($key);
      /** * Create redis Connection * @return Link/private Function connect () {try{$redis = new Redis (); $redis->connect ($this->_config[' host '), $this->_config[' Port ', $this->_config[' timeout '], $this->
      _config[' reserved '], $this->_config[' retry_interval ']);
      if (Empty ($this->_config[' auth ')) {$redis->auth ($this->_config[' auth '));
    $redis->select ($this->_config[' index '));
      }catch (Redisexception $e) {throw new Exception ($e->getmessage ());
    return false;
  return $redis;

 }//Class end?>

demo.php

<?php
require ' RedisLock.class.php ';

$config = Array (
  ' host ' => ' localhost ', '
  Port ' => 6379,
  ' index ' => 0,
  ' auth
  ' => ', ', ' Timeout ' => 1,
  ' reserved ' => NULL,
  ' retry_interval ' =>
;

Create a Redislock object
$oRedisLock = new Redislock ($config);

Define lock identification
$key = ' mylock ';

Get lock
$is _lock = $oRedisLock->lock ($key);

if ($is _lock) {
  echo ' get lock success<br> ';
  Echo ' do sth. <br> ';
  Sleep (5);
  Echo ' success<br> ';
  $oRedisLock->unlock ($key);

Get lock failed
}else{
  Echo ' request too frequently<br> ';

>

Test method:

Open two different browsers and access the demo.php in A,b

If the first access gets to the lock

Output

Get lock success
Do sth.
Success

Another failure to acquire the lock will output the request too frequently

Ensure that only one access is valid at the same time, effectively restricting concurrent access.

To avoid a deadlock caused by a sudden system error, add an expiration time when acquiring a lock and, if the expiration time has expired, release the lock, even if the lock state, to avoid the problem caused by the deadlock.
Source Download Address: Click to view

Related Article

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.