我有耗时的任务,我希望使用RabbitMQ将多个工作人员分开。
但是,当新的工作者/使用者附加到队列时,新工作者似乎不会接收先前已在队列中积压的任何消息。相反,新工作者似乎只接收在工作者订阅队列后到达的新消息。
也许我做错了什么,但是当新员工订阅队列时,我如何让RabbitMQ将积压的消息重新分发给新员工呢?
以下是一些用Scala编写的测试代码:
RabbitMQSendTest代码向RabbitMQ发送100条消息。 RabbitMQRecvTest模拟耗时的任务。 RabbitMQ似乎只向在消息到达之前订阅的客户端发送消息。但是,我希望队列中的现有消息在工作者订阅队列时重新分配给新工作者。
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer
object RabbitMQSendTest {
def main (args:Array[String]):Unit = {
val r = new RabbitMQSendTest ()
r.mainSendTest
}
}
class RabbitMQSendTest {
val QUEUE_NAME = "hello"
def mainSendTest () = {
try {
val factory = new ConnectionFactory ()
factory.setHost("127.0.0.1")
val connection = factory.newConnection()
val channel = connection.createChannel()
channel.queueDeclare(QUEUE_NAME, false, false, false, null)
channel.basicQos(5)
for (i <- (0 to 100)) {
val message = "Hello World " + i
channel.basicPublish("", QUEUE_NAME,null, message.getBytes())
println (" [x] Sent " + message)
Thread.sleep(100)
}
channel.close()
connection.close()
} catch
{
case ex:Exception => ex.printStackTrace()
}
}
}
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer
object RabbitMQRecvTest {
def main (args:Array[String]):Unit = {
val r = new RabbitMQTest ()
r.recvTest
}
}
class RabbitMQTest {
val QUEUE_NAME = "hello"
def recvTest () = {
val factory = new ConnectionFactory ()
factory.setHost("127.0.0.1")
val connection = factory.newConnection()
val channel = connection.createChannel()
channel.queueDeclare(QUEUE_NAME, false, false, false, null)
println ("[*] Waiting for messages")
val consumer = new QueueingConsumer (channel)
val autoAck = false
channel.basicConsume(QUEUE_NAME, autoAck, consumer)
while (true) {
val delivery = consumer.nextDelivery()
val message = new String (delivery.getBody())
println ("Received: " + message)
doWork (message)
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}
}
def doWork (message:String) = {
println ("Doing Work on : " + message)
Thread.sleep(10000)
}
}