配置文件参数说明
// 错误率 errorThresholdPercentage => 30, // 所有请求满10个 requestVolumeThreshold => 10, // 再次尝试一次间隔 sleepWindowInMilliseconds => 600000,
所有请求满10个, 错误率达到30%, 在断路器开启,且持续时间60秒
未来60秒内所有请求直接走 降级流程, 60秒后再次尝试一次
// 快照的有效期 healthSnapshotIntervalInMilliseconds => 1000 * 60, // 统计总周期 rollingStatisticalWindowInMilliseconds => 1000 * 60 * 10, // 统计窗口 rollingStatisticalWindowBuckets => 10,
最小统计粒度是窗口
每个窗口都有 成功数量和失败数量
统计总周期是10分钟,统计窗口是10个, 每一分钟会产生一个新窗口
统计监控状态的时候,会计算每个窗口的总请求次数, 失败请求次数,这个统计的结果叫做健康快照
快照的有效期是 60秒,如果这里设置成70秒的话, sleepWindowInMilliseconds设置成60秒 举例:10:01:01 检查状态, 创建了一个健康快照,健康快照反馈 错误率超过30%, 满足断路器开启条件,且断路器尝试一次间隔60秒 10:02:01 秒断路器有效期失效,健康快照并未更新,继续反馈错误率超过30%,(失败请求次数 / 总请求次数) * 100 > errorThresholdPercentage 则表示满足统计断路器的开启条件
return array(
'default' => array( // Default command configuration
....
),
'MyCommand' => array( // Command specific configuration
....
)
);
default 默认配置
MyCommand 自定义配置
自定义配置覆盖默认配置
简单使用示例:
use OdeskPhystrixAbstractCommand;
class MyCommand extends AbstractCommand
{
protected $name;
public function __construct($name)
{
$this->name = $name;
}
protected function run()
{
// 业务逻辑 ....
return 'Hello ' . $this->name;
}
protected function getFallback()
{
// 降级逻辑 ...
return 'Hello !!';
}
}
use ZendConfigConfig;
use OdeskPhystrixApcStateStorage;
use OdeskPhystrixCircuitBreakerFactory;
use OdeskPhystrixCommandMetricsFactory;
use OdeskPhystrixCommandFactory;
$config = new Config(require 'phystrix-config.php');
$stateStorage = new ApcStateStorage();
$circuitBreakerFactory = new CircuitBreakerFactory($stateStorage);
$commandMetricsFactory = new CommandMetricsFactory($stateStorage);
$phystrix = new CommandFactory(
$config, new ZendDiServiceLocator(),
$circuitBreakerFactory, $commandMetricsFactory,
new OdeskPhystrixRequestCache(),
new OdeskPhystrixRequestLog()
);
$myCommand = $phystrix->getCommand('MyCommand', 'Alex');
$result = $myCommand->execute();
更复杂一点的例子:
use OdeskPhystrixAbstractCommand;
# 自定义了如下配置
#'MyCommand' => array(
# 'fallback' => array(
# 'enabled' => false
# ),
# 'timeout' => 2000, // milliseconds
# )
class MyCommand extends AbstractCommand
{
protected $name;
public function __construct($name)
{
$this->name = $name;
}
protected function run()
{
$remoteAvatarService = $this->serviceLocator->get('xxx');
return $remoteAvatarService->getUserByName($this->name);
}
protected function prepare()
{
$remoteAvatarService = $this->serviceLocator->get('xxx');
if ($this->config->__isset('timeout')) {
$remoteAvatarService->setTimeout($this->config->get('timeout'));
}
}
protected function getFallback()
{
// 降级逻辑 ...
return false;
}
}
省略初始化代码, 参考简单示例....
$myCommand = $phystrix->getCommand('MyCommand', 'Alex');
$result = $myCommand->execute();
如果使用laravel的,建议修改下 ServiceLocator,传入app(),少加载点代码
建议使用apc扩展。
如果使用三方存储, 比如mysql,redis。在fpm下,每次请求都得重新统计错误率,建议对错误率进行下缓存。


