CQS:用CouchDB构建的队列系统

CQSCouchDB Queue Service)是一个用CouchDB构建的异步队列系统,如果你用过Amazon的SQS队列服务,那么你会发现CQS与SQS的api完全一致。

下面是使用node.js来操作CQS的一些例子:

安装:

 $ npm install cqs

初始化你的CQS模块:

// A normal import.
var cqs = require('cqs');

// Pre-apply my couch and db name.
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:
  // Found 2 queues:
  //   * a_queue
  //   * another_queue
})

创建一个队列:

// Just create with a name.
cqs.CreateQueue("important_stuff", function(error, queue) {
  if(!error)
    console.log("Important stuff queue is ready");
})

// Create with an options object.
var opts = { QueueName               : "unimportant_stuff"
           , DefaultVisibilityTimeout: 3600 // 1 hour
           };

cqs.CreateQueue(opts, function(error, queue) {
  if(!error)
    console.log("Created " + queue.name + " with timeout + " queue.VisibilityTimeout);

  // Output
  // Created unimportant_stuff with timeout 3600
})

添加一个队列消息:

// The convenient object API:
important_stuff.send(["keep these", "things", "in order"], function(error, message) {
  if(!error)
    console.log('Sent: ' + JSON.stringify(message.Body));

  // Output:
  // Sent: ["keep these","things","in order"]
})

cqs.SendMessage(important_stuff, "This message is important!", function(error, message) {
  if(!error)
    console.log('Sent message: ' + message.Body);

  // Output:
  // Sent message: This message is important!
})

// Or, just use the queue name.
cqs.SendMessage('some_other_queue', {going_to: "the other queue"}, function(error, message) {
  if(!error)
    console.log('Message ' + message.MessageId + ' is going to ' + message.Body.going_to);

  // Output:
  // Message a9b1c48bd6ae433eb7879013332cd3cd is going to the other queue
})

接收并处理一条队列消息:

// The convenient object API:
my_queue.receive(function(error, messages) {
  if(!error)
    console.log('Received message: ' + JSON.stringify(messages[0].Body));

  // Output:
  // Received message: <message body>
})

// The standard API, receiving multiple messages
cqs.ReceiveMessage(some_queue, 5, function(er, messages) {
  if(!error)
    console.log('Received ' + messages.length + ' messages');

  // Output:
  // Received <0 through 5> messages
})

删除一条队列消息:

// The convenient object API:
message.del(function(error) {
  // Message deletion never results in an error. If a message is successfully
  // deleted, it will simply never appear in the queue again.
  console.log('Message deleted!');
})

// The standard API:
cqs.DeleteMessage(my_message, function(error) {
  console.log('Message deleted');
})

来源:github.com

anyShare一切看了好文章不转的行为,都是耍流氓!
          

无觅相关文章插件,快速提升流量

分类 CouchDB · tag , , , , ,