共享記憶體 (Shared Memory) 允許多個行程存取同一塊實體記憶體區域,是進程間通訊 (IPC) 中速度最快的方式之一,因為資料交換不經由核心,避免 I/O 瓶頸。PHP 透過 shmop 擴充功能提供底層操作介面。
| 函數 | 用途 |
|---|---|
shmop_open() | 建立或開啟共享記憶體區段,回傳存取 ID |
shmop_write() | 向區段寫入資料 |
shmop_read() | 從區段讀取資料 |
shmop_size() | 取得區段大小 (位元組) |
shmop_delete() | 標記區段刪除 (實際釋放需所有行程關閉) |
shmop_close() | 關閉行程對區段的連結 |
<?php
$sysId = 864; // 系統 ID (整數,跨行程共用)
$mode = 'c'; // c: 建立或開啟並讀寫
$perm = 0755; // 權限 (八進位)
$size = 1024; // 位元組大小
// 1. 開啟/建立
$shmid = shmop_open($sysId, $mode, $perm, $size);
if ($shmid === false) die("建立失敗");
// 2. 寫入
$len = shmop_write($shmid, "Hello World!", 0);
echo "寫入 $len 位元組\n";
// 3. 讀取 (需知道長度)
$data = shmop_read($shmid, 0, shmop_size($shmid));
echo "讀取: $data\n";
// 4. 刪除與關閉
shmop_delete($shmid); // 標記刪除
shmop_close($shmid); // 釋放連結
?>
a:唯讀開啟既有區段w:讀寫開啟既有區段c:建立新區段,或開啟既有區段並讀寫 (最常用)n:建立新區段,若已存在則失敗為了簡化操作,可建立一個輕量封裝類別:
<?php
class SimpleSHM {
private $shmid;
private $sysId;
public function __construct(int $sysId = null) {
$this->sysId = $sysId ?? random_int(1000, 9999);
$this->shmid = shmop_open($this->sysId, 'c', 0755, 10240); // 10KB
if ($this->shmid === false) throw new RuntimeException("SHM 開啟失敗");
}
public function write(string $data): int {
return shmop_write($this->shmid, $data, 0);
}
public function read(): string {
return shmop_read($this->shmid, 0, shmop_size($this->shmid));
}
public function delete(): void {
shmop_delete($this->shmid);
}
public function __destruct() {
if ($this->shmid) shmop_close($this->shmid);
}
}
// 使用範例
$mem = new SimpleSHM(897);
$mem->write(json_encode(['user' => 'John', 'roles' => ['admin', 'editor']]));
$stored = json_decode($mem->read(), true);
print_r($stored);
igbinary > msgpack > json_encode > serialize (速度與體積權衡)共享記憶體是 PHP 開發者工具箱中被低估的利器,善用它能在適當場景大幅降低延遲、減輕資料庫壓力。