AMQP

The AMQP connector provides Akka Stream sources and sinks to connect to AMQP 0.9.1 servers (RabbitMQ, OpenAMQ, etc.).

AMQP 1.0 is currently not supported (Qpid, ActiveMQ, Solace, etc.).

Reported issues

Tagged issues at Github

Artifacts

sbt
libraryDependencies += "com.lightbend.akka" %% "akka-stream-alpakka-amqp" % "0.20"
Maven
<dependency>
  <groupId>com.lightbend.akka</groupId>
  <artifactId>akka-stream-alpakka-amqp_2.12</artifactId>
  <version>0.20</version>
</dependency>
Gradle
dependencies {
  compile group: 'com.lightbend.akka', name: 'akka-stream-alpakka-amqp_2.12', version: '0.20'
}

Usage

Connecting to AMQP server

All the AMQP connectors are configured using a AmqpConnectionProvider and a list of Declaration

There are several types of AmqpConnectionProvider:

  • AmqpLocalConnectionProvider which connects to the default localhost. It creates a new connection for each stage.
  • AmqpUriConnectionProvider which connects to the given AMQP URI. It creates a new connection for each stage.
  • AmqpDetailsConnectionProvider which supports more fine-grained configuration. It creates a new connection for each stage.
  • AmqpConnectionFactoryConnectionProvider which takes a raw ConnectionFactory. It creates a new connection for each stage.
  • AmqpCachedConnectionProvider which receive any other provider as parameter and caches the connection it provides to be used in all stages. By default it closes the connection whenever the last stage using the provider stops. Optionally, it takes automaticRelease boolean parameter so the connection is not automatically release and the user have to release it explicitly.

Sending messages to AMQP server

First define a queue name and the declaration of the queue that the messages will be sent to.

Scala
val queueName = "amqp-conn-it-spec-simple-queue-" + System.currentTimeMillis()
val queueDeclaration = QueueDeclaration(queueName)
Full source at GitHub
Java
final String queueName = "amqp-conn-it-spec-simple-queue-" + System.currentTimeMillis();
final QueueDeclaration queueDeclaration = QueueDeclaration.create(queueName);
Full source at GitHub

Here we used QueueDeclaration configuration class to create a queue declaration.

Create a sink, that accepts and forwards ByteStrings to the AMQP server.

Scala
val amqpSink = AmqpSink.simple(
  AmqpSinkSettings(connectionProvider)
    .withRoutingKey(queueName)
    .withDeclarations(queueDeclaration)
)
Full source at GitHub
Java
final Sink<ByteString, CompletionStage<Done>> amqpSink =
    AmqpSink.createSimple(
        AmqpSinkSettings.create(connectionProvider)
            .withRoutingKey(queueName)
            .withDeclarations(queueDeclaration));
Full source at GitHub

AmqpSink is a collection of factory methods that facilitates creation of sinks. Here we created a simple sink, which means that we are able to pass ByteStrings to the sink instead of wrapping data into OutgoingMessages.

Last step is to materialize and run the sink we have created.

Scala
val input = Vector("one", "two", "three", "four", "five")
Source(input).map(s => ByteString(s)).runWith(amqpSink).futureValue shouldEqual Done
Full source at GitHub
Java
final List<String> input = Arrays.asList("one", "two", "three", "four", "five");
Source.from(input).map(ByteString::fromString).runWith(amqpSink, materializer);
Full source at GitHub

Receiving messages from AMQP server

Create a source using the same queue declaration as before.

Scala
val amqpSource = AmqpSource.atMostOnceSource(
  NamedQueueSourceSettings(connectionProvider, queueName).withDeclarations(queueDeclaration),
  bufferSize = 10
)
Full source at GitHub
Java
final Integer bufferSize = 10;
final Source<IncomingMessage, NotUsed> amqpSource =
    AmqpSource.atMostOnceSource(
        NamedQueueSourceSettings.create(connectionProvider, queueName)
            .withDeclarations(queueDeclaration),
        bufferSize);
Full source at GitHub

The bufferSize parameter controls the maximum number of messages to prefetch from the AMQP server.

Run the source and take the same amount of messages as we previously sent to it.

Scala
val result = amqpSource.take(input.size).runWith(Sink.seq)
Full source at GitHub
Java
final CompletionStage<List<IncomingMessage>> result =
    amqpSource.take(input.size()).runWith(Sink.seq(), materializer);
Full source at GitHub

This is how you send and receive message from AMQP server using this connector.

Using Pub/Sub with an AMQP server

Instead of sending messages directly to queues, it is possible to send messages to an exchange and then provide instructions to AMQP server what to do with incoming messages to the exchange. We are going to use the fanout type of the exchange, which enables message broadcasting to multiple consumers. We are going to do that by using an exchange declaration for the sink and all of the sources.

Scala
val exchangeName = "amqp-conn-it-spec-pub-sub-" + System.currentTimeMillis()
val exchangeDeclaration = ExchangeDeclaration(exchangeName, "fanout")
Full source at GitHub
Java
final String exchangeName = "amqp-conn-it-spec-pub-sub" + System.currentTimeMillis();
final ExchangeDeclaration exchangeDeclaration =
    ExchangeDeclaration.create(exchangeName, "fanout");
Full source at GitHub

The sink for the exchange is created in a very similar way.

Scala
val amqpSink = AmqpSink.simple(
  AmqpSinkSettings(connectionProvider)
    .withExchange(exchangeName)
    .withDeclarations(exchangeDeclaration)
)
Full source at GitHub
Java
final Sink<ByteString, CompletionStage<Done>> amqpSink =
    AmqpSink.createSimple(
        AmqpSinkSettings.create(connectionProvider)
            .withExchange(exchangeName)
            .withDeclarations(exchangeDeclaration));
Full source at GitHub

For the source, we are going to create multiple sources and merge them using Akka Streams API.

Scala
val fanoutSize = 4

val mergedSources = (0 until fanoutSize).foldLeft(Source.empty[(Int, String)]) {
  case (source, fanoutBranch) =>
    source.merge(
      AmqpSource
        .atMostOnceSource(
          TemporaryQueueSourceSettings(
            connectionProvider,
            exchangeName
          ).withDeclarations(exchangeDeclaration),
          bufferSize = 1
        )
        .map(msg => (fanoutBranch, msg.bytes.utf8String))
    )
}
Full source at GitHub
Java
final Integer fanoutSize = 4;
final Integer bufferSize = 1;

Source<Pair<Integer, String>, NotUsed> mergedSources = Source.empty();
for (Integer i = 0; i < fanoutSize; i++) {
  final Integer fanoutBranch = i;
  mergedSources =
      mergedSources.merge(
          AmqpSource.atMostOnceSource(
                  TemporaryQueueSourceSettings.create(connectionProvider, exchangeName)
                      .withDeclarations(exchangeDeclaration),
                  bufferSize)
              .map(msg -> Pair.create(fanoutBranch, msg.bytes().utf8String())));
}
Full source at GitHub

We merge all sources into one and add the index of the source to all incoming messages, so we can distinguish which source the incoming message came from.

Such sink and source can be started the same way as in the previous example.

Using rabbitmq as an RPC mechanism

If you have remote workers that you want to incorporate into a stream, you can do it using rabbit RPC workflow RabbitMQ RPC

Scala
val amqpRpcFlow = AmqpRpcFlow.simple(
  AmqpSinkSettings(connectionProvider).withRoutingKey(queueName).withDeclarations(queueDeclaration)
)
Full source at GitHub
Java
final Flow<ByteString, ByteString, CompletionStage<String>> ampqRpcFlow =
    AmqpRpcFlow.createSimple(
        AmqpSinkSettings.create(connectionProvider)
            .withRoutingKey(queueName)
            .withDeclarations(queueDeclaration),
        1);
Full source at GitHub
Scala
val (rpcQueueF, probe) = Source(input)
  .map(s => ByteString(s))
  .viaMat(amqpRpcFlow)(Keep.right)
  .toMat(TestSink.probe)(Keep.both)
  .run
Full source at GitHub
Java
Pair<CompletionStage<String>, TestSubscriber.Probe<ByteString>> result =
    Source.from(input)
        .map(ByteString::fromString)
        .viaMat(ampqRpcFlow, Keep.right())
        .toMat(TestSink.probe(system), Keep.both())
        .run(materializer);
Full source at GitHub

Acknowledging messages downstream

Create a committable sink which returns

Scala
val amqpSource = AmqpSource.committableSource(
  NamedQueueSourceSettings(connectionProvider, queueName).withDeclarations(queueDeclaration),
  bufferSize = 10
)
Full source at GitHub
Java
final Integer bufferSize = 10;
final Source<CommittableIncomingMessage, NotUsed> amqpSource =
    AmqpSource.committableSource(
        NamedQueueSourceSettings.create(connectionProvider, queueName)
            .withDeclarations(queueDeclaration),
        bufferSize);
Full source at GitHub

Committable sources return CommittableIncomingMessage which wraps the IncomingMessage and exposes the methods ack and nack.

Use ack to acknowledge the message back to RabbitMQ. Ack takes an optional boolean parameter multiple indicating whether you are acknowledging the individual message or all the messages up to it.

Scala
val result = amqpSource
  .mapAsync(1)(cm => cm.ack().map(_ => cm))
  .take(input.size)
  .runWith(Sink.seq)
Full source at GitHub
Java
final CompletionStage<List<IncomingMessage>> result =
    amqpSource
        .mapAsync(1, cm -> cm.ack(false).thenApply(unused -> cm.message()))
        .take(input.size())
        .runWith(Sink.seq(), materializer);
Full source at GitHub

Use nack to reject a message. Apart from the multiple argument, nack takes another optional boolean parameter indicating whether the item should be requeued or not.

Scala
val result1 = amqpSource
  .take(input.size)
  .mapAsync(1)(cm => cm.nack().map(_ => cm))
  .runWith(Sink.seq)
Full source at GitHub
Java
final CompletionStage<List<CommittableIncomingMessage>> result1 =
    amqpSource
        .take(input.size())
        .mapAsync(1, cm -> cm.nack(false, true).thenApply(unused -> cm))
        .runWith(Sink.seq(), materializer);
Full source at GitHub

Running the example code

The code in this guide is part of runnable tests of this project. You are welcome to edit the code and run it in sbt.

Test code requires AMQP server running in the background. You can start one quickly using docker:

docker-compose up amqp

Scala
sbt
> amqp/testOnly *.AmqpConnectorsSpec
Java
sbt
> amqp/testOnly *.AmqpConnectorsTest
The source code for this page can be found here.