# Ubuntu/Debian
apt-get install php-dev php-pear libmsgpack-dev
# CentOS/RHEL
yum install php-devel php-pear msgpack-devel
pecl install msgpack
# 或源碼編譯
wget https://pecl.php.net/get/msgpack-2.2.0.tgz
tar xzf msgpack-2.2.0.tgz
cd msgpack-2.2.0
phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make && make install
pecl install yar
# 或源碼編譯
wget https://pecl.php.net/get/yar-2.3.2.tgz
tar xzf yar-2.3.2.tgz
cd yar-2.3.2
phpize
./configure --enable-msgpack --with-php-config=/usr/local/php/bin/php-config
make && make install
關鍵參數:--enable-msgpack 啟用 YAR 對 Msgpack 打包器的支持,不加則默認僅支持 JSON/serialize。
pecl install yaf
# php.ini 添加
extension=msgpack.so
extension=yar.so
extension=yaf.so
# 重載 PHP-FPM / Apache
systemctl reload php-fpm
php -i | grep msgpack
# 輸出應包含:
# yar.packager => msgpack => msgpack
php -m | grep -E 'yar|msgpack|yaf'
<?php
class YarKeywordClient
{
protected const HOST = 'kwdt.yarc.service.weibo.com';
protected const PORT = 7002;
public function detect(string $text, array $types = [1,2,3], int $returnText = 1): array
{
if (!class_exists('Yar_Client')) {
throw new RuntimeException('Yar_Client not available');
}
$client = new Yar_Client("tcp://" . self::HOST . ":" . self::PORT);
$client->opt(YAR_OPT_PACKAGER, 'msgpack'); // 顯式指定 msgpack
$client->opt(YAR_OPT_TIMEOUT, 5000); // 5秒超時
try {
return $client->detect($text, $returnText, $types);
} catch (Exception $e) {
error_log('YAR call failed: ' . $e->getMessage());
return ['error' => $e->getMessage()];
}
}
}
// 使用
$client = new YarKeywordClient();
$result = $client->detect('測試文本內容');
print_r($result);
/*
Array
(
[0] => -1
[1] => no keyword occured
)
*/
?>
<?php
class KeywordService
{
public function detect(string $text, int $returnText, array $types): array
{
// 業務邏輯:關鍵詞檢測...
return [-1, 'no keyword occured'];
}
}
$server = new Yar_Server(new KeywordService());
$server->handle();
| 問題 | 原因 | 解決 |
|---|---|---|
| Class 'Yar_Client' not found | yar.so 未加載或版本不匹配 | 檢查 php -m、php.ini、重載 PHP-FPM |
| Unsupported packager: msgpack | 編譯 YAR 時未加 --enable-msgpack | 重新編譯 YAR 並加入參數 |
| 連接超時 | 網絡不通、端口錯誤、防火牆 | telnet host port 測試連通性 |
| 返回亂碼 | 打包器不一致 | 客戶端 server 統一使用 msgpack |
Yar_Client::setOpt(YAR_OPT_CONNECT_TIMEOUT, ...) 配合連接池Yar_Concurrent_Client 批量發起調用,loop() 統一收集結果