xman12/single-flight
Composer 安装命令:
composer require xman12/single-flight
包简介
Single Flight library - prevents duplicate execution of the same operation
README 文档
README
A library for preventing duplicate execution of identical operations in PHP with support for various storage backends (Memory, Redis).
Description
Single Flight is a pattern that ensures the same operation (e.g., database query or external API request) executes only once, even if multiple processes or threads request it simultaneously. Other requests will wait for the result of the first execution.
Key Features
- Prevention of duplicate operations
- Inter-process synchronization
- Support for various storage backends (Memory, Redis)
- TTL (Time To Live) for automatic cache expiration
- Result caching between processes via Redis
- Cache stampede prevention
Installation
composer require xman12/single-flight
Usage
Basic Example (In-Memory)
<?php use SingleFlight\SingleFlight; $sf = new SingleFlight(); // This function will execute only once, // even if do() is called multiple times with the same key $result = $sf->do('fetch-user-1', function() { // Heavy operation (DB query, API call, etc.) return fetchUserFromDatabase(1); });
Using with Redis
<?php use SingleFlight\SingleFlight; use SingleFlight\Store\RedisStore; use Predis\Client; $redis = new Client([ 'scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379, ]); $store = new RedisStore($redis, 'my_app:'); $sf = new SingleFlight($store); // Result will be cached in Redis and available across processes $result = $sf->do('expensive-operation', function() { return performExpensiveOperation(); });
TTL (Time To Live)
<?php // Cache with 60 seconds TTL $result = $sf->do('temp-data', function() { return fetchTemporaryData(); }, 30.0, 60); // timeout 30s, TTL 60s // Or set default TTL $sf = new SingleFlight($store, null, 300); // 5 minutes by default
Using with Group
<?php use SingleFlight\Group; use SingleFlight\Store\RedisStore; $store = new RedisStore($redis, 'group:'); $group = new Group(null, $store); [$result, $wasExecuted] = $group->do('expensive-operation', function() { return performExpensiveOperation(); }); // $wasExecuted - true if this operation was actually executed, // false if we got a cached result if ($wasExecuted) { echo "Operation was executed"; } else { echo "Got cached result"; }
Cache Clearing
<?php // Clear specific key $sf->forget('fetch-user-1'); // Clear everything $sf->forget();
Cache Stampede Prevention
<?php use SingleFlight\SingleFlight; use SingleFlight\Store\RedisStore; $store = new RedisStore($redis); $sf = new SingleFlight($store); // Multiple simultaneous requests // Only ONE of them will execute the function, the rest will wait for the result $result = $sf->do('popular-content', function() { sleep(5); // Heavy operation return fetchPopularContent(); });
Project Structure
src/
├── SingleFlight.php # Main library class
├── Group.php # Class for grouping operations
├── Exception/
│ └── SingleFlightException.php # Library exceptions
└── Store/
├── StoreInterface.php # Interface for storage backends
├── MemoryStore.php # In-memory implementation
└── RedisStore.php # Redis implementation
Storage Backends (Stores)
MemoryStore
Stores data in the current process memory. Used by default.
use SingleFlight\Store\MemoryStore; $store = new MemoryStore(); $sf = new SingleFlight($store);
RedisStore
Stores data in Redis. Allows sharing results between processes.
use SingleFlight\Store\RedisStore; use Predis\Client; $redis = new Client('tcp://127.0.0.1:6379'); $store = new RedisStore($redis, 'prefix:'); // prefix is optional $sf = new SingleFlight($store);
Additional RedisStore Methods:
// Set key expiration time $store->expire('key', 60); // Get remaining time to live $ttl = $store->ttl('key'); // Increment/decrement $store->increment('counter', 1); $store->decrement('counter', 1);
Examples
See the examples/ folder for complete usage examples:
examples/redis_example.php- Working with Redisexamples/group_redis_example.php- Using Group with Redis
Running examples:
php examples/redis_example.php php examples/group_redis_example.php
Requirements
- PHP >= 8.1
- Symfony Lock Component >= 6.4
- Predis >= 2.2 (for RedisStore)
Testing
composer install vendor/bin/phpunit
For Redis tests, make sure Redis is running on 127.0.0.1:6379:
# Run Redis via Docker docker run -d -p 6379:6379 redis:alpine # Run tests vendor/bin/phpunit
API Reference
SingleFlight
// Constructor public function __construct( ?StoreInterface $store = null, // Storage backend (default MemoryStore) ?LockFactory $lockFactory = null, // Lock factory int $defaultTtl = 0 // Default TTL (0 = no expiration) ) // Execute operation once public function do( string $key, // Unique operation key callable $fn, // Function to execute float $timeout = 30.0, // Lock timeout ?int $ttl = null // TTL for result ): mixed // Check if cache exists public function has(string $key): bool // Clear cache public function forget(?string $key = null): void // Get storage backend public function getStore(): StoreInterface
Group
// Constructor public function __construct( ?SingleFlight $singleFlight = null, ?StoreInterface $store = null ) // Execute operation public function do( string $key, callable $fn, float $timeout = 30.0, ?int $ttl = null ): array // [result, wasExecuted] // Clear cache public function forget(?string $key = null): void
License
MIT
xman12/single-flight 适用场景与选型建议
xman12/single-flight 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 3 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 02 月 10 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 xman12/single-flight 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 xman12/single-flight 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 3
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 20
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-02-10