在这里你必须记住,rabbitMQ 通道不是线程安全的。所以创建一个单例类来处理所有这些rabbitmq操作
喜欢
我正在 SCALA 中编写代码示例
Object QueueManager{
val FACTORY = new ConnectionFactory
FACTORY setUsername (RABBITMQ_USERNAME)
FACTORY setPassword (RABBITMQ_PASSWORD)
FACTORY setVirtualHost (RABBITMQ_VIRTUALHOST)
FACTORY setPort (RABBITMQ_PORT)
FACTORY setHost (RABBITMQ_HOST)
conn = FACTORY.newConnection
var channel: com.rabbitmq.client.Channel = conn.createChannel
//here to decare consumer for queue1
channel.exchangeDeclare(EXCHANGE_NAME, "direct", durable)
channel.queueDeclare(QUEUE1, durable, false, false, null)
channel queueBind (QUEUE1, EXCHANGE_NAME, QUEUE1_ROUTING_KEY)
val queue1Consumer = new QueueingConsumer(channel)
channel basicConsume (QUEUE1, false, queue1Consumer)
//here to decare consumer for queue2
channel.exchangeDeclare(EXCHANGE_NAME, "direct", durable)
channel.queueDeclare(QUEUE2, durable, false, false, null)
channel queueBind (QUEUE2, EXCHANGE_NAME, QUEUE2_ROUTING_KEY)
val queue2Consumer = new QueueingConsumer(channel)
channel basicConsume (QUEUE2, false, queue2Consumer)
//here u should mantion distinct ROUTING key for each queue
def addToQueueOne{
channel.basicPublish(EXCHANGE_NAME, QUEUE1_ROUTING_KEY, MessageProperties.PERSISTENT_TEXT_PLAIN, obj.getBytes)
}
def addToQueueTwo{
channel.basicPublish(EXCHANGE_NAME, QUEUE2_ROUTING_KEY, MessageProperties.PERSISTENT_TEXT_PLAIN, obj.getBytes)
}
def getFromQueue1:Delivery={
queue1Consumer.nextDelivery
}
def getFromQueue2:Delivery={
queue2Consumer.nextDelivery
}
}
我已经为 2 个队列编写了一个代码示例,你可以像上面一样添加更多队列............