• Stars
    star
    101
  • Rank 337,086 (Top 7 %)
  • Language
    PHP
  • License
    MIT License
  • Created about 8 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

RedisLock for PHP is a synchronization mechanism for enforcing limits on access to a resource in an environment where there are many threads of execution. A lock is designed to enforce a mutual exclusion concurrency control policy.

MIT license Latest Stable Version Total Downloads

RedisLock v1.0.3 for PHP >= 5.5

About

RedisLock for PHP is a synchronization mechanism for enforcing limits on access to a resource in an environment where there are many threads of execution. A lock is designed to enforce a mutual exclusion concurrency control policy. Based on redis.

Usage

Create a new instance of RedisLock

<?php
require 'vendor/autoload.php';

use RedisLock\RedisLock;
use RedisClient\ClientFactory;
use RedisClient\RedisClient;

// Create a new Redis instance
$Redis = ClientFactory::create([
    'server' => 'tcp://127.0.0.1:6379'
]);

$Lock = new RedisLock(
    $Redis, // Instance of RedisClient,
    'key', // Key in storage,
);

Usage for lock a process

<?php
require 'vendor/autoload.php';

use RedisLock\RedisLock;
use RedisClient\ClientFactory;
use RedisClient\RedisClient;

// Create a new Redis instance
$Redis = ClientFactory::create([
    'server' => 'tcp://127.0.0.1:6379'
]);

// ...

/**
 * Safe update json in Redis storage
 * @param Redis $Redis
 * @param string $key
 * @param array $array
 * @throws Exception
 */
function updateJsonInRedis(RedisClient $Redis, $key, array $array) {
    // Create new Lock instance
    $Lock = new RedisLock($Redis, 'Lock_'.$key, RedisLock::FLAG_DO_NOT_THROW_EXCEPTIONS);

    // Acquire lock for 2 sec.
    // If lock has acquired in another thread then we will wait 3 second,
    // until another thread release the lock. Otherwise it throws a exception.
    if (!$Lock->acquire(2, 3)) {
        throw new Exception('Can\'t get a Lock');
    }

    // Get value from storage
    $json = $Redis->get($key);
    if (!$json) {
        $jsonArray = [];
    } else {
        $jsonArray = json_decode($json, true);
    }

    // Some operations with json
    $jsonArray = array_merge($jsonArray, $array);

    $json = json_encode($jsonArray);
    // Update key in storage
    $Redis->set($key, $json);

    // Release the lock
    // After $lock->release() another waiting thread (Lock) will be able to update json in storage
    $Lock->release();
}

updateJsonInRedis($Redis, 'json-key', ['for' => 1, 'bar' => 2]);
updateJsonInRedis($Redis, 'json-key', ['for' => 42, 'var' => 2016]);

Methods

RedisLock :: __construct ( RedisClient $Redis , string $key [, int $flags = 0 ] )


Create a new instance of RedisLock.

Method Pameters
  1. RedisClient $Redis - Instanse of RedisClient
  2. string $key - name of key in Redis storage. Only locks with the same name will compete with each other for lock.
  3. int $flags, default = 0
    • RedisLock::FLAG_DO_NOT_THROW_EXCEPTIONS - use this flag, if you don't want catch exceptions by yourself. Do not use this flag, if you want have a full control on situation with locks. Default behavior without this flag - all Exceptions will be thrown.
Example
$Lock = new RedisLock($Redis, 'lockName');
// or
$Lock = new RedisLock($Redis, 'lockName', RedisLock::FLAG_DO_NOT_THROW_EXCEPTIONS);

bool RedisLock :: acquire ( int|float $lockTime , [ float $waitTime = 0 [, float $sleep = 0.005 ] ] )


Try to acquire lock for $lockTime seconds. If lock has acquired in another thread then we will wait $waitTime seconds, until another thread release the lock. Otherwise method throws a exception (if FLAG_DO_NOT_THROW_EXCEPTIONS is not set) or result. Returns true on success or false on failure.

Method Pameters
  1. int|float $lockTime - The time for lock in seconds, the value must be >= 0.01.
  2. float $waitTime, default = 0 - The time for waiting lock in seconds. Use 0 if you don't wait until lock release.
  3. float $sleep, default = 0.005 - The wait time between iterations to check the availability of the lock.
Example
$Lock = new RedisLock($Redis, 'lockName');
$Lock->acquire(3, 4);
// ... do something
$Lock->release();

bool RedisLock :: update ( int|float $lockTime )


Set a new time for lock if it is acquired already. Returns true on success or false on failure. Method can throw Exceptions.

Method Pameters
  1. int|float $lockTime - Please, see description for method RedisLock :: acquire
Example
$Lock = new RedisLock($Redis, 'lockName');
$Lock->acquire(3, 4);
// ... do something
$Lock->update(3);
// ... do something
$Lock->release();

bool RedisLock :: isAcquired ( )


Check this lock for acquired. Returns true on success or false on failure.

bool RedisLock :: isLocked ( )


Check this lock for acquired and not expired, and active yet. Returns true on success or false on failure. Method can throw Exceptions.

bool RedisLock :: isExists ()


Does lock exists or acquired anywhere? Returns true if lock is exists or false if is not.

Installation

Composer

Download composer:

wget -nc http://getcomposer.org/composer.phar

and add dependency to your project:

php composer.phar require cheprasov/php-redis-lock

Running tests

To run tests type in console:

./vendor/bin/phpunit

Something doesn't work

Feel free to fork project, fix bugs and finally request for pull

More Repositories

1

php-redis-client

RedisClient is a fast, fully-functional and user-friendly client for Redis, optimized for performance. RedisClient supports the latest versions of Redis starting from 2.6 to 6.0
PHP
126
star
2

js-qrcode

The library is for generating QR codes like SVG, HTML5 Canvas, PNG and JPG files, or text.
JavaScript
53
star
3

json-colors

JSON list of colors
30
star
4

jThread

Simple way to use multi-threading in javascript. Based on web workers.
JavaScript
17
star
5

php-parallel

The class allows you to run multiple operations parallel in different processes and send results to the main process. Useful if you need to run multiple independent operations simultaneously, instead of sequential execution, or if you run several independent queries, for example, queries to different data bases.
PHP
17
star
6

php-cli-args

Class CliArgs helps to get cli options/params from the command line argument list easy.
PHP
13
star
7

php-memcached-tags

MemcachedTags for PHP is a mechanism for adding tags to keys in Memcached. It is very useful, if you need to select or delete some keys by tags. And tags are really useful for group invalidation.
PHP
12
star
8

php-memcached-lock

MemcachedLock for PHP is a synchronization mechanism based on Memcached for enforcing limits on access to a resource in an environment where there are many threads of execution.
PHP
9
star
9

lua-scripts-for-redis

Some Lua scripts for redis
4
star
10

js-base-converter

The library allows to convert a number between arbitrary bases.
JavaScript
4
star
11

php-simple-profiler

Simple Profiler for PHP projects.
PHP
3
star
12

js-web-animation

Simple class WebAnimation for perform an animation on the web via JavaScript. It is based on requestAnimationFrame for performance.
JavaScript
2
star
13

ts-url-query-params

TypeScript
2
star
14

specification-protocol-userpro

Universal serialization protocol (USERPRO)
2
star
15

ts-cv

My CV (TypeScript, React)
TypeScript
2
star
16

Dockerfiles

Dockerfile
2
star
17

go-rasp-fan

Go
2
star
18

go-image-resizer

Go
2
star
19

js-uk-tax-calculator

JavaScript
2
star
20

js-the-bee-game

JavaScript
1
star
21

js-chart

JavaScript
1
star
22

tc-otravo

PHP
1
star
23

js-worker-thread

The WorkerThread wraps a Web Worker with a Promise, also the class creates a worker script on the fly (without having to create separate worker files). You can "inline" your worker function in the same js file as main logic.
JavaScript
1
star
24

py-pdf-splitter

Python
1
star
25

js-canvas-show

JavaScript
1
star
26

ts-react-global-state

TypeScript
1
star
27

php-extra-mocks

ExtraMocks are a tools that give extra functionality for Mocks.
PHP
1
star
28

ts-react-qrcode

TypeScript
1
star
29

chrome-ext-youtube-ads

JavaScript
1
star
30

ts-json-web-worker

The library for parse / stringify JSON in different thread via Web Workers
TypeScript
1
star
31

ts-jsbt

TypeScript
1
star
32

php-benchmark-tests

PHP
1
star