CQS(CouchDBQueueService)是一個用CouchDB構建的非同步隊列系統,如果你用過Amazon的SQS隊列服務,那麼你會發現CQS與SQS的api完全一致。下面學步園小編來講解下怎樣使用node.js來操作CQS?
怎樣使用node.js來操作CQS
安裝:
$npminstallcqs
初始化你的CQS模塊:
//Anormalimport.
varcqs=require('cqs');
//Pre-applymycouchanddbname.
cqs=cqs.defaults({"couch":"https://user:password@example.iriscouch.com"
,"db":"cqs_queue"
});
列出所有的隊列:
cqs.ListQueues(function(error,queues){
console.log("Found"+queues.length+"queues:");
queues.forEach(function(queue){
console.log("*"+queue.name);
})
//Output:
//Found2queues:
//*a_queue
//*another_queue
})
創建一個隊列:
//Justcreatewithaname.
cqs.CreateQueue("important_stuff",function(error,queue){
if(!error)
console.log("Importantstuffqueueisready");
})
//Createwithanoptionsobject.
varopts={QueueName:"unimportant_stuff"
,DefaultVisibilityTimeout:3600//1hour
};
cqs.CreateQueue(opts,function(error,queue){
if(!error)
console.log("Created"+queue.name+"withtimeout+"queue.VisibilityTimeout);
//Output
//Createdunimportant_stuffwithtimeout3600
})
怎樣使用node.js來操作CQS
添加一個隊列消息:
//TheconvenientobjectAPI:
important_stuff.send(["keepthese","things","inorder"],function(error,message){
if(!error)
console.log('Sent:'+JSON.stringify(message.Body));
//Output:
//Sent:["keepthese","things","inorder"]
})
cqs.SendMessage(important_stuff,"Thismessageisimportant!",function(error,message){
if(!error)
console.log('Sentmessage:'+message.Body);
//Output:
//Sentmessage:Thismessageisimportant!
})
//Or,justusethequeuename.
cqs.SendMessage('some_other_queue',{going_to:"theotherqueue"},function(error,message){
if(!error)
console.log('Message'+message.MessageId+'isgoingto'+message.Body.going_to);
//Output:
//Messagea9b1c48bd6ae433eb7879013332cd3cdisgoingtotheotherqueue
})
接收並處理一條隊列消息:
//TheconvenientobjectAPI:
my_queue.receive(function(error,messages){
if(!error)
console.log('Receivedmessage:'+JSON.stringify(messages[0].Body));
//Output:
//Receivedmessage:
})
//ThestandardAPI,receivingmultiplemessages
cqs.ReceiveMessage(some_queue,5,function(er,messages){
if(!error)
console.log('Received'+messages.length+'messages');
//Output:
//Received<0through5>messages
})
刪除一條隊列消息:
//TheconvenientobjectAPI:
message.del(function(error){
//Messagedeletionneverresultsinanerror.Ifamessageissuccessfully
//deleted,itwillsimplyneverappearinthequeueagain.
console.log('Messagedeleted!');
})
//ThestandardAPI:
cqs.DeleteMessage(my_message,function(error){
console.log('Messagedeleted');
})
以上就是關於「怎樣使用node.js來操作CQS」的內容,希望對大家有用。更多資訊請關注學步園。學步園,您學習IT技術的優質平台!