现在的位置: 首页 > 数据库 > 正文

怎样使用node.js来操作CQS

2020年07月02日 数据库 ⁄ 共 2541字 ⁄ 字号 评论关闭

  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技术的优质平台!

抱歉!评论已关闭.