我正在尝试使用RabbitMQ Publisher和Consumer做一个简单的应用程序,生成器是用Java编写的,而消费者是在Scala中。
这是我正在使用的发布者,它成功地将数据插入rabbitMQ服务器中的“queue1”队列:
String queue="queue1";
String exchange="queue1";
String routing_key="queue1";
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(queue, true, false, false, null);
channel.exchangeDeclare(exchange, "direct");
channel.queueBind(queue,exchange,routing_key);
channel.basicQos(1);
String msg = "Hello";
channel.basicPublish(exchange,routing_key_one, new AMQP.BasicProperties.Builder().contentType("text/plain").deliveryMode(1).priority(0).
build(),msg.getBytes());
channel.close();
connection.close();
现在的问题是,我在一个单独的脚本上有一个Consumer,但我不能让它返回我从发布者发送的“msg”字符串;我只能将consumer-tag作为返回值。这是我的消费者:
import com.rabbitmq.client.{ConnectionFactory,Connection,Channel,Consumer,DefaultConsumer,Envelope,BasicProperties}
val rabbit_host="localhost"
val queue="queue1"
val exchange="queue1"
val routing_key="queue1"
val factory: ConnectionFactory = new ConnectionFactory()
factory.setHost (rabbit_host)
val connection: Connection = factory.newConnection()
val channel: Channel = connection.createChannel()
channel.queueBind(queue_name, exchange, routing_key, null)
channel.basicQos(1)
val consumer:Consumer=new DefaultConsumer(channel){
def handleDelivery(consumerTag: String, envelope: Envelope, properties: BasicProperties, body: Array[Byte]):String ={
new String(body,"UTF-8")
}
}
val msg: String = channel.basicConsume(queue_name,true, consumer)
channel.close()
connection.close()
如果我打印“msg”,这就是我得到的值:“amq.ctag-miRiLnyTcsq9MwzHyVshZw”
所以我的问题是,有没有办法让我得到“hello”(原始值)作为basicConsume函数的返回?
感谢您的时间。
答案 0 :(得分:0)
根据文件
val msg: String = channel.basicConsume(queue_name,true, consumer)
返回
与新消费者相关联的consumerTag
由于rabbitMq的异步性质,等待消息并不容易。您可以尝试使用Promise并阻止结果
val p = Promise[String]()
val f = p.future
val consumer:Consumer=new DefaultConsumer(channel){
def handleDelivery(consumerTag: String, envelope: Envelope, properties: BasicProperties, body: Array[Byte]):String ={
val parsedBody = new String(body,"UTF-8")
p.success(parsedBody)
}
}
val msg: String = Await.result(f, 5 seconds)