code-orange/redis-counting-semaphore

redis的分布式计数信号量实现

v1.2 2020-10-30 12:36 UTC

This package is auto-updated.

Last update: 2024-08-29 03:52:57 UTC


README

redis-counting-semaphore 是一个PHP的计数信号量实现包。它使用redis作为中心代理。

安装

使用composer安装redis-counting-semaphore

composer require code-orange/redis-counting-semaphore

使用方法

首先,确保你已经有一个 Predis 连接实例。

你可以创建并尝试获取一个信号量,如下所示

<?php
use CodeOrange\RedisCountingSemaphore\Semaphore;

$client = new Predis\Client();

// Create a counting semaphore with a limit of 3
$sem = new Semaphore($client, 'semaphore-name', 3);
if ($sem->acquire(0.1, 10)) {
	// Obtained the semaphore
	use_limited_resource();
	$sem->release();
} else {
	// We weren't able to get a semaphore, even though we tried 10 times
	// And slept for 0.1 seconds in between tries
}

API

/**
 * Semaphore constructor.
 * @param Client $client Predis client with an open connection
 * @param string $name Name of the semaphore
 * @param int $limit The amount of resources this semaphore protects
 * @param int $timeout Timeout of an acquired semaphore, in seconds
 */
public Semaphore(Client $client, $name, $limit = 1, $timeout = 10);

/**
 * Try to acquire a semaphore
 *
 * @param float $sleep Number of seconds to sleep between retries. If null, this function will not retry but return immediately.
 * @param int $retries Number of times to retry before giving up
 * @return bool Whether or not the semaphore was acquired correctly
 */
public function acquire($sleep = null, $retries = null);

/**
 * Release this semaphore
 *
 * @return void
 */
public function release();

/**
 * Refresh the semaphore
 *
 * @return bool Whether or not we still have the semaphore
 */
public function refresh();