计数器基于 Swoole 的原子计数,适合统计 QPS、在线数、任务进度这类「只加不减也无所谓」的值。
用法
use houze\swoole\Atomic;
$atomic = Atomic::run();
// 先建,不存在时创建并给初值
if (!$atomic->has('request_total')) {
$atomic->create('request_total', 0);
}
// 自增
$atomic->setInc('request_total');
// 自减
$atomic->setDec('request_total');
// 读取
$total = $atomic->get('request_total');
可用方法
| 方法 | 作用 |
|---|---|
create($key, $init) | 创建计数器 |
has($key) | 是否存在 |
setInc($key) / setDec($key) | 加减 |
get($key) / set($key, $v) | 取值 / 赋值 |
cmpset($key, $old, $new) | CAS,用于无锁并发控制 |
delete($key) | 删除 |
和 Table 的区别
Atomic:只能存整数,操作是原子的,适合计数;Table:能存字符串,适合映射关系。
注意
数据在共享内存里,进程重启即清零。要持久化的统计请落 Redis 或数据库;Atomic 只适合「运行时指标」。