-->

Play Framework send message via rabbit mq

2020-07-23 04:47发布

问题:

Does anybody out there using rabbitmq with Play Framework?

I have an AI written in Scala using Play Framework. And I have a mean stack, which handles a nosql database. I'd like to send json messages via rabbitmq to that AI.

I already got things going with nodejs and rabbitmq, but now that i want to connect to play I might need your help.

Has someone any experience with rabbitmq and play or some practical Advices?

Thanks!

回答1:

You can use the standard Java library to send messages to RabbitMQ like this:

val factory = new ConnectionFactory()
factory.setUri(serverUri)
val channel = connection.createChannel()
channel.queueDeclare(queue, true, false, false, null)
channel.basicPublish("", queue, true, false, null, data)

When using this in Play, you'd probably put all the logic up to basicPublish inside its own class and inject that instance into your Controller, so that you can use a persistent connection to Rabbit.

Since all your seem to be doing is taking json from a request and pushing it into Rabbit, you don't even have to deal with serialization and can just take the text body from the Request and pass it as the data payload of basicPublish (unless you want to perform validation of the input before passing it on).