a distributed-redis-lock implementation for hyperf2.*

Overview

hyperf-redis-lock

English | 中文

an easy redis-based distributed-lock implementation for hyperf 2.*。 This extension features distributed-lock includes block and unblock distributed-lock.

Principle

The command in Redis is atomic.so we use set to make sure that your application executes sequentially. The Redis version before 2.8 does't support the option ex in set command. so we just use setnx+expire instead.>> Version 1.* The Redis version after 2.8 supports the option ex in set command. so we use set nx ex>> Version 2.*

so version 2.* supports the version of redis after 2.8. version 1.* supports all the versions of redis.

Redis version

redis-server --version

Install

Run composer require lysice/hyperf-redis-lock

Usage

init the redis object

    /**
     * @var RedisProxy
     */
    protected $redis;

    public function __construct(RedisFactory $redisFactory)
    {
        $this->redis = $redisFactory->get('default');
    }
  • non-block lock we try to acquire the lock then return the result directly.If acquire the lock, execute the Closure and return the Closure's result. or return false;
public function lock(ResponseInterface $response)
    {
        $lock = new RedisLock($this->redis, 'lock', 20);
        $res = $lock->get(function () {
            sleep(10);
            return [123];
        });
        return $response->json($res);
    }
  • blocking lock we try acquire the lock first. 1.if failed we try to acquire the lock every 250 ms util timeout(the time we waiting for is bigger than the expire time you set in your application) 2.if success then execute the closure and return the result of closure.
    Tips: if timeout occurs in the process of application you need to catch the exception LockTimeoutException to handle this situation. for example:
/**
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function lockA(ResponseInterface $response)
    {
        try {
            $lock = new RedisLock($this->redis, 'lock', 4);
            $res = $lock->block(4, function () {
                return [456];
            });
            return $response->json(['res' => $res]);
        // catch the exception
        } catch (LockTimeoutException $exception) {
            var_dump('lockA lock check timeout');
            return $response->json(['res' => false, 'message' => 'timeout']);
        }
    }

Finally

Contributing

Feel free to create a fork and submit a pull request if you would like to contribute.

Bug reports

Raise an issue on GitHub if you notice something broken.

You might also like...
🔌 A Doctrine DBAL Driver implementation on top of Swoole Coroutine PostgreSQL extension

Swoole Coroutine PostgreSQL Doctrine DBAL Driver A Doctrine\DBAL\Driver implementation on top of Swoole\Coroutine\PostgreSQL. Getting started Install

A minimalistic implementation of asynchronous SQL for PHP.

libSQL A minimalistic implementation of asynchronous SQL for PHP. Installation via DEVirion Install the DEVirion plugin and start your server. This wi

Eloquent Repository implementation

Eloquent Repository Eloquent Repository using nilportugues/repository as foundation. Installation Use Composer to install the package: $ composer requ

Eloquent MongoDB Repository Implementation

Eloquent MongoDB Repository Eloquent MongoDB Repository using nilportugues/repository as foundation, using jenssegers/mongodb. Installation Use Compos

Mutex lock implementation

Yii Mutex This package provides mutex implementation and allows mutual execution of concurrent processes in order to prevent "race conditions". This i

Distributed PSR-16 cache implementation for PHP 6 that uses browser cookies to store data

cookiecache Cache beyond the edge with cookies! This library provides a distributed PSR-16 compatible cache implementation for PHP 6 that uses browser

Simple library that abstracts different metrics collectors. I find this necessary to have a consistent and simple metrics (functional) API that doesn't cause vendor lock-in.

Metrics Simple library that abstracts different metrics collectors. I find this necessary to have a consistent and simple metrics API that doesn't cau

Lock library to provide serialized execution of PHP code.

Requirements | Installation | Usage | License and authors | Donations php-lock/lock This library helps executing critical code in concurrent situation

GitHub Action that diffs composer.lock between current branch and default branch
GitHub Action that diffs composer.lock between current branch and default branch

github-action-composer.lock-diff GitHub Action that diffs composer.lock between current branch and default branch Options (inputs) This action support

A fast, lock-free, shared memory user data cache for PHP

Yac is a shared and lockless memory user data cache for PHP.

Async Redis client implementation, built on top of ReactPHP.

clue/reactphp-redis Async Redis client implementation, built on top of ReactPHP. Redis is an open source, advanced, in-memory key-value database. It o

Redis repository implementation for Laravel Queue Batch

Laravel RedisBatchRepository Replaces default Illuminate\Bus\DatabaseBatchRepository with implementation based on Redis. Requirements: php 8 laravel 8

This is an implementation of PSR specification. It allows you to send and consume message with Redis store as a broker.

This is an implementation of PSR specification. It allows you to send and consume message with Redis store as a broker.

Asynchronous & Fault-tolerant PHP Framework for Distributed Applications.
Asynchronous & Fault-tolerant PHP Framework for Distributed Applications.

Kraken PHP Framework ~ Release the Kraken! Note: This repository contains the core of the Kraken Framework. If you want to start developing new applic

🐺 Asynchronous Task Queue Based on Distributed Message Passing for PHP.
🐺 Asynchronous Task Queue Based on Distributed Message Passing for PHP.

🐺 Asynchronous Task Queue Based on Distributed Message Passing for PHP.

a php client for distributed transaction framework dtm. 分布式事务管理器dtm的php客户端

a client for distributed transaction manager dtm dtmcli 是分布式事务管理器dtm的客户端sdk dtm分布式事务管理服务 DTM是一款跨语言的开源分布式事务管理器,优雅的解决了幂等、空补偿、悬挂等分布式事务难题。提供了简单易用、高性能、易水平扩

🚀 A distributed content delivery network (DCDN) integration plugin for wordpress
🚀 A distributed content delivery network (DCDN) integration plugin for wordpress

DCDN Engine - WordPress DCDN Plugin Simply integrate a Distributed Content Delivery Network (DCDN) into your WordPress site. Preview Plugin Installati

This example shows how to estimate pi, using generated random numbers that uniformly distributed.
This example shows how to estimate pi, using generated random numbers that uniformly distributed.

php-estimatepi This example shows how to estimate pi, using generated random numbers that uniformly distributed. Every pair of numbers produced will b

A cross-language remote procedure call(RPC) framework for rapid development of high performance distributed services.

Motan Overview Motan is a cross-language remote procedure call(RPC) framework for rapid development of high performance distributed services. Related

Comments
  • getDateTimeAfterInterval 返回是是Carbon,但是addRealSeconds 接受的是int

    getDateTimeAfterInterval 返回是是Carbon,但是addRealSeconds 接受的是int

    https://github.com/Lysice/hyperf-redis-lock/blob/2d26f27bd412c4dc644457e8c4a97ece8a5c50c3/src/InteractsWithTime.php#L32

    这里不是应该是?:

    $delay = $this->getDateTimeAfterInterval($delay);
            return $delay instanceof \DateTimeInterface
                ? $delay->getTimestamp()
                : Carbon::now()->addRealSeconds($delay->getTimestamp() - $this->currentTime())->getTimestamp();
    
    opened by xuyudong 0
Releases(v2.1)
Owner
lysice
The wind arises among the duckweed.
lysice
a php client for distributed transaction framework dtm. 分布式事务管理器dtm的php客户端

a client for distributed transaction manager dtm dtmcli 是分布式事务管理器dtm的客户端sdk dtm分布式事务管理服务 DTM是一款跨语言的开源分布式事务管理器,优雅的解决了幂等、空补偿、悬挂等分布式事务难题。提供了简单易用、高性能、易水平扩

null 29 Jan 7, 2023
High performance distributed database for mysql

High performance distributed database for mysql, define shardings by velocity&groovy scripts, can be expanded nodes flexible...

brucexx 33 Dec 13, 2022
A Redis based, fully automated and scalable database cache layer for Laravel

Lada Cache A Redis based, fully automated and scalable database cache layer for Laravel Contributors wanted! Have a look at the open issues and send m

Matt 501 Dec 30, 2022
Поддержка очередей Redis (и на RabbitMq, и на Filesystem, и через DBAL) в Битриксе

Модуль для Битрикса, организующий работу с очередями через Redis (и не только) Поддерживаемый транспорт: Redis RabbitMq Filesystem DBAL Установка comp

Fedy 4 Aug 20, 2021
A Redis bundle for Symfony supporting Predis and PhpRedis

RedisBundle About This bundle integrates Predis and PhpRedis into your Symfony 3.4+ application, providing a fast and convenient interface to Redis. U

Henrik Westphal 1k Dec 22, 2022
This is raw connection between redis server and django python app

Django_Redis This repository contains the code for this blogpost. Running the Application Clone the repository git clone https://github.com/xxl4tomxu9

Tom Xu 1 Sep 15, 2022
Baum is an implementation of the Nested Set pattern for Laravel's Eloquent ORM.

Baum Baum is an implementation of the Nested Set pattern for Laravel 5's Eloquent ORM. For Laravel 4.2.x compatibility, check the 1.0.x branch branch

Estanislau Trepat 2.2k Jan 3, 2023
A data mapper implementation for your persistence model in PHP.

Atlas.Orm Atlas is a data mapper implementation for persistence models (not domain models). As such, Atlas uses the term "record" to indicate that its

null 427 Dec 30, 2022
Adjacency List’ed Closure Table database design pattern implementation for the Laravel framework.

ClosureTable This is a database manipulation package for the Laravel 5.4+ framework. You may want to use it when you need to store and operate hierarc

Yan Ivanov 441 Dec 11, 2022
A drop-in Doctrine ORM 2 implementation for Laravel 5+ and Lumen

Laravel Doctrine ORM A drop-in Doctrine ORM 2 implementation for Laravel 5+ $scientist = new Scientist( 'Albert', 'Einstein' ); $scientist->a

Laravel Doctrine 777 Dec 17, 2022