1.7.5 在Server中使用swoole_table

1.7.5增加了swoole_table共享内存表,swoole_table可以与swoole_server结合使用。使用方法也很简单

  • 在swoole_server->start()之前创建swoole_table对象。并存入全局变量或者类静态变量/对象属性中。
  • 在worker/task进程中获取table对象,并使用

只有在swoole_server->start()之前创建的table对象才能在子进程中使用
swoole_table构造方法中指定了最大容量,一旦超过此数据容量将无法分配内存导致set操作失败。所以使用swoole_table之前一定要规划好数据容量

$table = new swoole_table(1024);
$table->column('fd', swoole_table::TYPE_INT);
$table->column('from_id', swoole_table::TYPE_INT);
$table->column('data', swoole_table::TYPE_STRING, 64);
$table->create();

$serv = new swoole_server('127.0.0.1', 9501);
//将table保存在serv对象上
$serv->table = $table;

$serv->on('receive', function ($serv, $fd, $from_id, $data) {
    $ret = $serv->table->set($fd, array('from_id' => $data, 'fd' => $fd, 'data' => $data));
});

$serv->start();


  • qwe

    请问swoole_table的数据容量怎么理解?比如“$table = new swoole_table(1024)” ,1024是1024条数据,还是指存储的数据大小不能超过1024?1024字节?1024k?

  • killernb

    task中使用table

    class server{
        private  $ws;
        public function getlist($ws,$fd){
            $list=[];
            foreach($this->ws->userList as $k=>$v){
                $list[$k]=$v;
            }
            $ws->push($fd, json_encode($list));
            return $list;
        }
        public function setlist($uid){
            $this->ws->userList->set('x'.$uid,array("gid"=>$uid,"fd"=>$uid,'info'=>$uid));
        }
        public function closeClient($ws,$fd){
            $this->ws->userList->del('x'.$fd);
        }
        public function start(){
            $this->ws = new swoole_websocket_server("0.0.0.0", 5050);
            $this->ws->userList = new swoole_table(10240);
            $this->ws->userList->column('gid', swoole_table::TYPE_STRING,32);
            $this->ws->userList->column('fd', swoole_table::TYPE_INT);
            $this->ws->userList->column('info', swoole_table::TYPE_STRING, 1024*10);
            $this->ws->userList->create();
    
            $this->ws->on('message', function ($ws, $frame) {
                print_r($frame);
                $ws->task($frame);
            });
            $this->ws->on('task', function ($ws, $task_id, $from_id, $frame) {
                $this->setlist($frame->fd);
                print_r($this->getlist($ws,$frame->fd));
                return;
            });
            $this->ws->on('close', function ($ws, $fd) {
                $this->closeClient($ws,$fd);
            });
    
            $this->ws->on('finish', function ($ws, $task_id, $data) { });
            $this->ws->set(array('task_worker_num' => 16));
            $this->ws->start();
    
        }
    }
    $server=new server();
    $server->start();
    

  • Yuanjm

    swoole_talbe 内存尺寸

    https://wiki.swoole.com/wiki/page/257.html