在Magento中利用redis做消息队列
首先在配置文件中配置好redis的相关信息:
<config>
<global>
<redis_queue>
<host>127.0.0.1</host>
<port>6379</port>
<db>3</db>
</redis_queue>
</global>
</config>
消息队列的核心消息发送和取出:
private $_queueName = 'queue';
public function __construct($queueName)
{
if($queueName){
$this->_queueName .= '_'.$queueName;
}
}
public function send($method, $params = [], $delay = false)
{
if (!is_array($params)) {
Mage::throwException('Params must be an array');
}
//拼出消息
$message = [];
$message['method'] = $method;
$message['params'] = $params;
$message = json_encode($message);
try {
//从配置文件中取出Redis信息
$options = Mage::getConfig()->getNode('global/redis_queue')->asArray();
$options['delay'] = 0;
if ($delay === true) {
$options['delay'] = 1;
}
$options['queue_name'] = $this->_queueName;
//将整理好的信息带到Queue/Adapter/Redis文件下的构造方法中
$adapter = Mage::getModel('queue/adapter_redis', $options);
//将整理的信息放入到消息队列中
$adapter->send($message);
} catch (Exception $e) {
Mage::logException($e);
Mage::log('队列发送失败', null, 'queueException.log');
}
}
public function receive($delay = false)
{
//从配置文件中取出Redis信息
$options = Mage::getConfig()->getNode('global/redis_queue')->asArray();
$options['delay'] = 0;
if ($delay === true) {
$options['delay'] = 1;
}
$options['qu eue_name'] = $this->_queueName;
//将整理好的信息带到Queue/Adapter/Redis文件下的构造方法中
$adapter = Mage::getModel('queue/adapter_redis', $options);
//将redis消息队列中存入的信息取出
$msgs = $adapter->receive();
return $msgs;
}
const DEFAULT_RECEIVE_TIMEOUT = 30;
const DEFAULT_QUEUE_KEY = 'queue';
private $_client = null;
private $_queue_key = self::DEFAULT_QUEUE_KEY;
//由上一个方法调用时带过来的redis信息在构造函数中做处理
public function __construct($options)
{
if(!$this->_client){
$host = $options['host'];
$port = $options['port'];
$db = $options['db'];
$this->_client = new Credis_Client($host, $port);
$this->_client->select($db);
}
$queue_name = $options['queue_name'];
$this->_queue_key = $queue_name;
if($options['delay']){
$this->_queue_key = $queue_name.'_delay';
}
return $this->_client;
}
public function send($message)
{
//将消息从左送入到redis消息队列中
$this->_client->lPush($this->_queue_key, $message);
}
// 删除,并获得该列表中的最后一个元素,或阻塞,直到有一个可用
public function receive($maxMessages = null, $timeout = null)
{
if ($maxMessages === null) {
$maxMessages = 1;
}
if ($timeout === null) {
$timeout = self::DEFAULT_RECEIVE_TIMEOUT;
}
//从php.ini文件取出配置'default_socket_timeout'的值
$socket_timeout = ini_get('default_socket_timeout');
if($timeout >= $socket_timeout) {
$timeout = $socket_timeout - 2;
}
$msgs = [];
if ($maxMessages > 0 ) {
for ($i = 0; $i < $maxMessages; $i++) {
//将消息队列从右侧取出
$msgs[] = $this->_client->brPop($this->_queue_key, $timeout);
}
}
return $msgs;
}