Swoole中内存操作以及协程

Swoole_table是一个基于共享内存和锁实现的超高性能,并发数据结构

```````php

$table = new swoole_table(1024);
//内存表增加一列
$table->column('id', $table::TYPE_INT, 4);
$table->column('name', $table::TYPE_STRING , 64);
$table->column('age', $table::TYPE_INT, 3);
$table->create();

//设置行的数据
$table->set('chuangxiang', [
    'id' => 1,
    'name' => 'chuangxiang',
    'age' => 30,
]);

//另外一种设置行的数据
$table['chuangxiang2'] = [
    'id' => 2,
    'name' => 'shaoguan',
    'age' => 35,
];

$table->incr('chuangxiang', 'age', 2); //增加
$table->decr('chuangxiang2', 'age', 2); //减少
$table->del('chuangxiang'); //删除

print_r($table->get('chuangxiang'));
print_r($table['chuangxiang2']);

```````

上面的案例创建了一张内存表,内存一旦释放,内存表即消失

内存表用于共享很方便

协程(redis)

Swoole在2.0开始内置协程(Coroutine)的能力,提供了具备协程能力IO接口(统一在命名空间Swoole\Coroutine\*)。

开发者可以无感知的用同步的代码编写方式达到异步IO的效果和性能,避免了传统异步回调所带来的离散的代码逻辑和陷入多层回调中导致代码无法维护。

  • 把普通功能的实现方式变成协程
  • 必须使用在onRequet,onReceive,onConnect回调中使用

````````php

$http = new Swoole_http_server('0.0.0.0', 8001);

$http->on('request', function($request, $response){
    //获取redis里面的key的内容,然后输出浏览器
    $redis = new Swoole\Coroutine\Redis();
    $redis->connect('localhost', 6379);
    $value = $redis->get($request->get['a']);
    $response->header("Content-Type", "text/plain");
    $response->end($value);
});

$http->start();

````````

$request->get[‘a’]  //获得通过地址带参传的值

猜你喜欢

转载自blog.csdn.net/qq_36289732/article/details/82561689