我正在尝试使用由 Windows Azure SDK for PHP 提供的 REST 代理与 Azure 队列进行交互。虽然有大量的代码示例 here ,我想检查队列是否存在,以便在向队列添加消息之前可以在必要时创建它。
try {
// setup connection string for accessing queue storage
$connectionString = 'DefaultEndpointsProtocol=' . PROTOCOL . ';AccountName=' . ACCOUNT_NAME . ';AccountKey=' . ACCOUNT_KEY;
// create queue REST proxy
$queueRestProxy = ServicesBuilder::getInstance()->createQueueService($connectionString);
// create message
$queueRestProxy->createMessage(QUEUE_NAME, 'Hello World!');
} catch(ServiceException $e){
// Handle exception based on error codes and messages.
// Error codes and messages are here:
// http://msdn.microsoft.com/en-us/library/windowsazure/dd179446.aspx
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
创建队列就这么简单......
$queueRestProxy->createQueue(QUEUE_NAME);
我应该在创建消息之前简单地包含队列创建代码,还是有更有效的方法来在与队列交互之前确定队列是否存在?
最佳答案
通常在其他 Windows Azure SDK 中,我见过像 createQueueIfNotExists
这样的方法,但令我惊讶的是 PHP SDK 中缺少此方法。基本上,该函数的工作方式是尝试创建一个队列。如果存储中存在同名队列,存储服务会抛出冲突(409)
错误。
由于不存在此函数,因此您可以执行相同的操作,即尝试在自己的 try/catch block 内创建队列并检查错误代码。如果错误代码是 409,则继续,否则重新抛出异常。类似于下面的代码:
try {
// setup connection string for accessing queue storage
$connectionString = 'DefaultEndpointsProtocol=' . PROTOCOL . ';AccountName=' . ACCOUNT_NAME . ';AccountKey=' . ACCOUNT_KEY;
// create queue REST proxy
$queueRestProxy = ServicesBuilder::getInstance()->createQueueService($connectionString);
try {
// now try to create the queue.
$queueRestProxy->createQueue(QUEUE_NAME);
} catch(ServiceException $e){
$code = $e->getCode();
//Now check if the $code is 409 - Conflict. If the error code is indeed 409, you continue otherwise throw the error
}
// create message
$queueRestProxy->createMessage(QUEUE_NAME, 'Hello World!');
} catch(ServiceException $e){
// Handle exception based on error codes and messages.
// Error codes and messages are here:
// http://msdn.microsoft.com/en-us/library/windowsazure/dd179446.aspx
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
附注我没有尝试执行该代码,因此可能会引发错误。这只是为了给您一个想法。
关于php - 使用 REST 代理 (PHP) 检查 Azure 队列是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21538040/