RamblingCookieMonster / PSRabbitMq

PowerShell module to send and receive messages from a RabbitMq server
http://ramblingcookiemonster.github.io/RabbitMQ-Intro/
MIT License
47 stars 29 forks source link

Question about a "retrieve loop" to drain a queue with multiple items in it. #23

Closed NealWalters closed 6 years ago

NealWalters commented 6 years ago

If I have a queue with 3 items in it, should this drain the queue and display each item?

$maxLoops = 5 
For ($i=0; $i -le $maxLoops; $i++) 
{
    $Incoming = Wait-RabbitMqMessage -Exchange $Exchange -Key $QueueName -QueueName $QueueName -Timeout 20 -vhost base @Params
    Write-Host $Incoming 
}

It pauses 20 seconds, then the Write-Host statement displays only the first item in the queue From the RabbitMQ web interface, I see the queue empty after running this.

Thanks, Neal

NealWalters commented 6 years ago

Seems like it needs a callback function passed to it, as in this Java example:

https://stackoverflow.com/questions/31743430/rabbitmq-multiple-messages-and-single-consumer

boolean autoAck = false;
channel.basicConsume(queueName, autoAck, "myConsumerTag",
 new DefaultConsumer(channel) {
     @Override
     public void handleDelivery(String consumerTag,
                                Envelope envelope,
                                AMQP.BasicProperties properties,
                                byte[] body)
         throws IOException
     {
         String routingKey = envelope.getRoutingKey();
         String contentType = properties.getContentType();
         long deliveryTag = envelope.getDeliveryTag();
         // (process the message components here ...)
         channel.basicAck(deliveryTag, false);
     }
 });

Neal

NealWalters commented 6 years ago

Okay, now I found you have a Start-RabbitMQListener - but I don't understand where it sends the message to variables so I can handle them.

Neal

derekmwright commented 6 years ago

Here's how I use the listener (I encode my messages as json)

Start-RabbitMqListener -ComputerName 'rabbitmqhost.example.com' `
                       -Exchange 'powershell' `
                       -Key 'script_execution' `
                       -QueueName 'script_execution' `
                       -AutoDelete $false `
                       -Durable $false `
                       -Credential $creds `
                       -Ssl Tls12 | %{ # Might want to change this to a For-Each as I guess this syntax is bad manners...
    $req = $_ | ConvertFrom-Json
    # Do stuff with $req
    }

This will run forever and each time an object is retreived the logic in for For-Each loop is executed.

NealWalters commented 6 years ago

Thanks that's what I was looking for! I didn't know you were supposed to pipe it to a for-each loop (and I didn't remember the % sign was a short cut for for-each).

Neal