Swoole高性能共享內存 Table
先定結構在進行操作數據(原生swoole操作):
```
//創建表
$table = new Swoole\Table(1024);
$table->column("id", Swoole\Table::TYPE_INT);
$table->column("name", Swoole\Table::TYPE_STRING);
$table->column("money", Swoole\Table::TYPE_FLOAT);
$table->create();
//添加數據
$table->set("zq", [
'id' => 1,
'name' => "zhiqiang",
'money' => 100,
]);
//獲取一行數據
$table->get("zq");
// 修改數據
// 字段遞增
$table->incr("zq","money",2);
//遞減
$table->decr("zq","money",2);
// 返回 table 中存在的條目數。
$table->count();
//遍歷table中的數據
foreach($table as $item){
var_dump($item);
}
```
think-swoole中的操作:
先對table表結構進行初始化config\swoole.php
```
'tables' => [
'user'=>[
'size'=>1024,
'columns'=>[
[
'name'=>'id',
'type'=>\Swoole\Table::TYPE_INT
],
[
'name'=>'name',
'type'=>\Swoole\Table::TYPE_STRING,
'size'=>32
],
[
'name'=>'money',
'type'=>\Swoole\Table::TYPE_FLOAT
],
],
],
],
```
操作數據:
```
$table = app('swoole.table.user');
$table->set("zq", [
'id' => 1,
'name' => "zhiqiang",
'money' => 100
]);
//獲取一行數據
$table->get("zq");
// 修改數據
// 字段遞增
$table->incr("zq", "money", 2);
//遞減
$table->decr("zq", "money", 2);
// 返回 table 中存在的條目數。
$table->count();
//遍歷table中的數據
foreach ($table as $item) {
var_dump($item);
}
// 檢查 table 中是否存在某一個 key。
$table->exist('zq');
//獲取實際占用內存尺寸,單位字節
$table->momorySize();
```
RPC
RPC(Remote Procedure Call):遠程過程調用,它是一種通過網絡從遠程計算機程序上請求服務,而不需要了解底層網絡技術的思想。
詳細介紹:https://developer.51cto.com/a...
解決分布式系統中,服務之間的調用問題。
遠程調用時,要能夠像本地調用一樣方便,讓調用者感知不到遠程調用的邏輯。
節點角色說明:
Server: 暴露服務的服務提供方
Client: 調用遠程服務的服務消費方
Registry: 服務注冊與發現的注冊中心
think-swoole實現RPC功能
服務器端
接口定義app/rpc/interfaces/UserInterface.php
```
<?php
namespace app\rpc\interfaces;
interface UserInterface
{
public function create();
public function find(int $id);
}
```
實現接口app/rpc/services/UserService.php
```
<?php
namespace app\rpc\services;
use app\rpc\interfaces\UserInterface;
class UserService implements UserInterface
{
public function create()
{
// TODO: Implement create() method.
return "service create success";
}
public function find(int $id)
{
// TODO: Implement find() method.
return $id. "查詢數據遍歷";
}
}
```
注冊rpc服務config/swoole.php
```
'rpc' => [
'server' => [
//開啟rpc服務
'enable' => true,
//rpc端口
'port' => 9000,
'services' => [
//注冊服務
\app\rpc\services\UserService::class
],
],
// 如果填寫也是可以調用其他服務端
'client' => [
],
],
```
啟動服務端:php think swoole start / php think swoole:rpc
客戶端
```
'rpc' => [
'server' => [
],
'client' => [
'tp6'=>[
//服務端的ip地址
'host'=>'127.0.0.1',
//服務端對應的端口
'port'=>'9000'
]
// 更多服務端
],
],
```
運行php think rpc:interface生成RPC接口文件app\rpc.php
```
?php
/**
* This file is auto-generated.
*/
declare(strict_types=1);
namespace rpc\contract\tp6;
interface UserInterface
{
public function create();
public function find(int $id);
}
return ['tp6' => ['rpc\contract\tp6\UserInterface']];
```
在控制器調用
```
public function index(\rpc\contract\tp6\UserInterface $user)
{
//
$user->find(1);
//$user->create();
}
```