在cli下运行消费数据,需要保持redis断线重连,虽然redis可以直接传递参数长连接,但是如果redis服务器异常关闭后再重启则需要重启php脚本,比较麻烦,所以写了一个redis断线重连简单版。
<?php
class PRedis
{
/**
* options
* @var array
*/
protected $options = ['host' => '127.0.0.1', 'port' => 6379, 'password' => '', 'select' => 0, 'timeout' => 0, 'expire' => 0, 'persistent' => false, 'prefix' => ''];
/**
* handler
* @var null
*/
protected $handler = null;
/**
* Redis constructor.
* @param array $options
* @throws Exception
*/
public function __construct($options = [])
{
$this->options = array_merge($this->options, $options);
$this->connect(false);
}
/**
* connect
* @param $throw
* @throws RedisException
*/
protected function connect($throw = true)
{
try {
$this->handler = new \Redis();
if ($this->options['persistent']) {
$this->handler->pconnect($this->options['host'], $this->options['port'], $this->options['timeout'], 'persistent_id_' . $this->options['select']);
} else {
$this->handler->connect($this->options['host'], $this->options['port'], $this->options['timeout']);
}
if ('' != $this->options['password']) {
$this->handler->auth($this->options['password']);
}
if (0 != $this->options['select']) {
$this->handler->select($this->options['select']);
}
} catch (\RedisException$exception) {
if ($throw) {
throw $exception;
}
}
}
/**
* __call
* @param $name
* @param $args
* @return mixed
* @throws
*/
public function __call($name, $args)
{
try {
set_error_handler(function ($errno, $errStr) {
restore_error_handler();
throw new RedisException($errStr, $errno);
});
return $this->handler->{$name}(...$args);
} catch (\RedisException$exception) {
echo "断线重连:" . $exception->getMessage() . PHP_EOL;
$this->connect(false);
return false;
}
}
}
$redis = new PRedis();
$redisKey = 'key';
while (true) {
//set
$redis->set($redisKey, rand(1, 99));
//get
$value = $redis->get($redisKey);
if ($value) {
echo $value . PHP_EOL;
}
//sleep
sleep(1);
}可以在断线重连异常中适当ping()来决定是否真正去连接,并且建议增加间隔多久连接一次。tp中mysql的断线重连是依赖于错误信息的关键字,或许在redis中断线重连也可以参考,毕竟异常不一定都是redis断开连接,可以从异常信息中提取关键字来精确分析,当然ping一下更简单。也没有来得及去看redis官方文档说明,凑合能用。
开发com组件可以用c++,vc++,net,我比较熟悉net,演示用dnet(1).创建项目:启动vs2017,新建项目,选择Visual C# ->Windows桌面->类库通用windows(2). 修改Com项目:点击 项目->项目属性,再点击应用程序->程序集信息,...
逛公众号文章看到文章"php实现事件监听与触发的方法,你用过吗?",我就好奇了,php又不是asp.net的webform,哪里来的服务端事件监听。于是学习了一波。先看下监听类:class Event { /** &nbs...
ThinkPHP中有一个debug调试功能,能输出报错文件的信息,并能看到这个函数被哪些函数调用,从框架的启动开始记录,特别方便调试。于是研究了下它的底层给予了实现。<?php //--框架核心--Start //框架内置错误处理 function errDealWith($er...
最近在公司开发一个新的项目假设项目域名是a.com,需要接入b.com的单点登陆系统。(1).首先我们会在a.com的登陆页面用iframe引入b.com来显示登陆界面,实际上登陆验证操作都是在b.com上面(2).当b.com验证通过,会在前端ajax请求a.com的回调地址,这个回调地址目的就是...
在编写多进程的实例中我在每个进程中使用如下代码://调用等待信号的处理器 while (true) { pcntl_signal_dispatch(); }开启5个进程,cpu直接100%修正之后的代码://调用等待信号的处理器 while&...
<?php /** * @throws Exception */ function curl() { throw new \Exception('err...