在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官方文档说明,凑合能用。
上家公司开发医院挂号系统,系统采用GBK编码。ajax发送的中文用户名让PHP保存为cookie出现乱码的解决方案。1.Javascript变量var user=document.getElementById('user').innerText; user=escape(u...
if($_SERVER['REQUEST_METHOD'] == 'POST') { echo('This is post '); } elseif ($_SERVER['...
Redis提供了发布订阅功能,可以用于消息的传输,Redis的发布订阅机制包括三个部分,发布者(publisher),订阅者(subscriber)和频道(channel)。 发布者和订阅者都是Redis客户端,Channel则为Redis服务器端,发布者将消息发送到某个的频道,订阅了这个...
主要原理是通过PHP创建多个子进程,在子进程中发送进程闹钟信号,然后再监听闹钟信号中继续发送闹钟信号。同时通过父进程设置非阻塞运行。代码如下:<?php /** * 订单任务 */ class Order { &n...
posix_ttyname - 获取当前终端设备名称。<?php var_dump( posix_ttyname(STDOUT) );我们启动一个终端,执行上面的代码输出:/dev/tty1我们再启动一个终端,执行上面的代码输...
经常我们下载国外资源容易被墙,可以通过php脚本获取远程文件流然后输出给我们的浏览器来下载。<?php //设置下载文件的url $url = 'https://mirrors.huaweicloud.com/ubuntukylin/ubuntukylin-19....