Data Sharing

As mentioned previously, Laravel applications run in different worker processes. There's one important concept to keep in mind: Variables are not shared across different processes.

3. Data Sharing - 图1

Each worker has their own variables and memory allocations. Keeping Laravel in memory doesn't mean we can share data among different processes.

There are, though, many options to share resources between processes:

  • Databases like MySQL and Redis
  • APCu - APC User Cache
  • Swoole Table
  • Any other I/O based alternatives

Swoole Table

In swoole_http.php, you can customize your own Swoole Table:

  1. use Swoole\Table;
  2.  
  3. 'tables' => [
  4. // define your table name here
  5. 'table_name' => [
  6. // table rows number
  7. 'size' => 1024,
  8. // column name, column type and column type size are optional for int and float type
  9. 'columns' => [
  10. ['name' => 'column_name1', 'type' => Table::TYPE_INT],
  11. ['name' => 'column_name2', 'type' => Table::TYPE_STRING, 'size' => 1024],
  12. ]
  13. ],
  14. ]

There are three column types of Swoole Table:

  • TYPE_INT: 1,2,4,8
  • TYPE_FLOAT: 8
  • TYPE_STRING: the nth power of 2

Usage

  1. <?php
  2.  
  3. use SwooleTW\Http\Table\Facades\Table;
  4.  
  5. class Foo
  6. {
  7. // get a table by its name
  8. $table = Table::get('table_name');
  9.  
  10. // update a row of the table by key
  11. $table->set('key', 'value');
  12.  
  13. // get a row of the table by key
  14. $table->get('key');
  15.  
  16. // delete a row of the table by key
  17. $table->del('key');
  18.  
  19. // check if a row is existed by key
  20. $table->exist('key');
  21.  
  22. // count the rows in the table
  23. $table->count();
  24. }

Check more Swoole Table usages here: https://www.swoole.co.uk/docs/modules/swoole-table