介绍
swoole_table一个基于共享内存和锁实现的超高性能,并发数据结构。用于解决多进程/多线程数据共享和同步加锁问题。
Swoole的Memory模块其实都是用于进程之间的通信,不同进程可以通过Memory模块共享数据。
使用步骤
1. 创建内存表对象
swoole_table->__construct(int $size, float $conflict_proportion = 0.2)
注意:
size最小为1024,且必须是1024的正整数倍数。
2. 内存表增加一列
swoole_table->column(string $name, int $type, int $size = 0);
-
$name
指定字段的名称 -
$type
指定字段类型,支持3种类型,
swoole_table::TYPE_INT,
swoole_table::TYPE_FLOAT
swoole_table::TYPE_STRING -
$size
指定字符串字段的最大长度,单位为字节。字符串类型的字段必须指定$size
注意:
-
swoole_table::TYPE_INT默认为4个字节,可以设置1,2,4,8一共4种长度
-
swoole_table::TYPE_STRING设置后,设置的字符串不能超过此长度
-
swoole_table::TYPE_FLOAT会占用8个字节的内存
3. 申请内存空间
function swoole_table->create()
定义好表的结构后,执行create向操作系统申请内存,创建表。
调用create之前不能使用set、get等数据读写操作方法。
调用create之后不能使用column方法添加新字段。
系统内存不足,申请失败,create返回false。
申请内存成功,create返回true。
swoole_table使用共享内存来保存数据,在创建子进程前,务必要执行swoole_table->create()。
swoole_server中使用swoole_table,swoole_table->create() 必须在swoole_server->start()前执行。
4. 设置或更新一行的数据
// 函数风格
swoole_table->set(string $key, array $value)
// 数组风格
$table[key] = [
field => value,
....
];
-
$key
,数据的key,相同的$key
对应同一行数据,如果set同一个key,会覆盖上一次的数据 -
$value
,必须是一个数组,必须与字段定义的$name
完全相同 -
swoole_table->set() 可以设置全部字段的值,也可以只修改部分字段
-
swoole_table->set() 未设置前,该行数据的所有字段均为空
5. 获取一行的数据
// 函数风格
swoole_table->get(string $key, string $field = null);
// 数组风格
$table[key];
-
如果
$key
不存在,将返回false -
当指定了
$field
时仅返回该字段的值,而不是整个记录
6. 自增
function swoole_table->incr(string $key, string $column, mixed $incrby = 1);
-
$key
指定数据的key,如果$key
对应的行不存在,默认列的值为0 -
$column
指定列名,仅支持浮点型和整型字段 -
$incrby
增量,默认为1。如果列为整形,$incrby
必须为int型,如果列为浮点型,$incrby
必须为float类型 -
失败返回false,成功返回最终的结果数值
7. 自减
function swoole_table->decr(string $key, string $column, mixed $decrby = 1);
-
$key
指定数据的key,如果$key
对应的行不存在,默认列的值为0 -
$column
指定列名,仅支持浮点型和整型字段 -
$decrby
减量,默认为1。如果列为整形,$decrby
必须为int型,如果列为浮点型,$decrby
必须为float类型 -
失败返回false,成功返回最终的结果数值
8. 是否存在某个key
int swoole_table->exist(string $key);
9. 删除数据
swoole_table->del(string $key)
$key
对应的数据不存在,将返回false
成功删除返回true。
10. 统计table条数
int function swoole_table->count();
完整例子
<?php
// 1.创建内存表
$table = new swoole_table(1024);
// 2.内存表增加一列
$table->column('id', $table::TYPE_INT, 4);
$table->column('name', $table::TYPE_STRING, 64);
$table->column('age', $table::TYPE_INT, 3);
// 3.申请内存空间
$table->create();
// 4.设置行的数据
$table->set('tim_test',['id'=>1,'name'=>'tim','age'=>23]);
// 另一种形式设置
$table['chen_test'] = [
'id' => 2,
'name' => 'chen',
'age' => 21
];
// 5.数据增加
//$table->incr('chen_test','age',2);
// 6.数据减少
$table->decr('tim_test','age',2);
// 7.查询数据
var_dump($table->exist('chen_test'));
// 8.删除数据
var_dump($table->del('chen_test'));
// 9.查询数据
var_dump($table->exist('chen_test'));
// 10. 获取行的数据
print_r($table->get('tim_test'));
// 另一种形式获取
//print_r($table['chen_test']);