|
| 1 | +Redis counting semaphore [](https://packagist.org/packages/code-orange/redis-counting-semaphore) [](https://packagist.org/packages/code-orange/redis-counting-semaphore) [](https://packagist.org/packages/code-orange/redis-counting-semaphore) [](https://packagist.org/packages/code-orange/redis-counting-semaphore) |
| 2 | +======================== |
| 3 | + |
| 4 | +`redis-counting-semaphore` is a package with a counting semaphore implementation for PHP. |
| 5 | +It uses redis as a central broker. |
| 6 | + |
| 7 | +# Installation |
| 8 | + |
| 9 | +To install redis-counting-semaphore with composer: |
| 10 | + |
| 11 | +``` |
| 12 | +composer require code-orange/redis-counting-semaphore |
| 13 | +``` |
| 14 | + |
| 15 | +# Usage |
| 16 | + |
| 17 | +First, make sure you have a [Predis](https://github.com/nrk/predis) connection instance. |
| 18 | + |
| 19 | +You can create and attempt to obtain a semaphore like so: |
| 20 | + |
| 21 | +```php |
| 22 | +<?php |
| 23 | +use CodeOrange\RedisCountingSemaphore\Semaphore; |
| 24 | + |
| 25 | +$client = new Predis\Client(); |
| 26 | + |
| 27 | +// Create a counting semaphore with a limit of 3 |
| 28 | +$sem = new Semaphore($client, 'semaphore-name', 3); |
| 29 | +if ($sem->acquire(0.1, 10)) { |
| 30 | + // Obtained the semaphore |
| 31 | + use_limited_resource(); |
| 32 | + $sem->release(); |
| 33 | +} else { |
| 34 | + // We weren't able to get a semaphore, even though we tried 10 times |
| 35 | + // And slept for 0.1 seconds in between tries |
| 36 | +} |
| 37 | +``` |
| 38 | + |
| 39 | +## API |
| 40 | + |
| 41 | +```php |
| 42 | +/** |
| 43 | + * Semaphore constructor. |
| 44 | + * @param Client $client Predis client with an open connection |
| 45 | + * @param string $name Name of the semaphore |
| 46 | + * @param int $limit The amount of resources this semaphore protects |
| 47 | + * @param int $timeout Timeout of an acquired semaphore, in seconds |
| 48 | + */ |
| 49 | +public Semaphore(Client $client, $name, $limit = 1, $timeout = 10); |
| 50 | + |
| 51 | +/** |
| 52 | + * Try to acquire a semaphore |
| 53 | + * |
| 54 | + * @param float $sleep Number of seconds to sleep between retries. If null, this function will not retry but return immediately. |
| 55 | + * @param int $retries Number of times to retry before giving up |
| 56 | + * @return bool Whether or not the semaphore was acquired correctly |
| 57 | + */ |
| 58 | +public function acquire($sleep = null, $retries = null); |
| 59 | + |
| 60 | +/** |
| 61 | + * Release this semaphore |
| 62 | + * |
| 63 | + * @return void |
| 64 | + */ |
| 65 | +public function release(); |
| 66 | + |
| 67 | +/** |
| 68 | + * Refresh the semaphore |
| 69 | + * |
| 70 | + * @return bool Whether or not we still have the semaphore |
| 71 | + */ |
| 72 | +public function refresh(); |
| 73 | +``` |
0 commit comments