Skip to content

Publish and receive with Artemis

By the end of this you will have run a bus on a real AMQP 1.0 broker, seen an event delivered under AtLeastOnce, and watched a message that a handler keeps declining arrive on the dead-letter queue after its last attempt.

You need Docker, Go, and network access to pull modules. It was run against the adapter's main with go/messaging v0.9.0 and apache/artemis:2.57.0-alpine.

1. Start the broker

A stock Artemis is not enough. The adapter declares SurvivesRestart only when the broker persists delivery counts and syncs its journal, and the module's test fixture ships a broker.xml that turns those on and sets the address settings used below.

$ git clone https://gitlab.com/phpboyscout/go/messaging-amqp
$ docker run -d --rm --name artemis -p 5672:5672 \
    -e ARTEMIS_USER=artemis -e ARTEMIS_PASSWORD=artemis \
    -v "$PWD/messaging-amqp/test/integration/testdata/broker.xml:/var/lib/artemis-instance/etc-override/broker.xml:ro" \
    apache/artemis:2.57.0-alpine

Wait for Server is now active in docker logs artemis. The override's a.# address settings give every subject under a. a dead-letter address, DLQ, with a queue behind it, and a max-delivery-attempts of 10.

2. Write the program

$ mkdir greeter && cd greeter && go mod init example/greeter
$ go get gitlab.com/phpboyscout/go/messaging-amqp

An at-least-once subscription attaches to a durable queue the operator has made. You are the operator for this tutorial, so give the adapter a Topology that creates the queue the first time it is named. A real deployment would not: see Prepare Artemis for at-least-once.

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    goamqp "github.com/Azure/go-amqp"
    "gitlab.com/phpboyscout/go/envelope"

    "gitlab.com/phpboyscout/go/messaging"

    amqp "gitlab.com/phpboyscout/go/messaging-amqp"
)

// createOnResolve makes the durable queue the first time a subscription
// names it. Tutorial only: in production the operator owns the queue.
type createOnResolve struct{}

func (createOnResolve) Queue(ctx context.Context, sess *goamqp.Session, address string, spec messaging.SourceSpec) (string, error) {
    err := amqp.Artemis{}.Create(ctx, sess, amqp.QueueSpec{
        Name: spec.DurableName, Address: address, RoutingType: "MULTICAST", Durable: true,
    })

    return spec.DurableName, err
}

func main() {
    ctx := context.Background()

    backend, err := amqp.New(ctx, amqp.Settings{
        URL:      "amqp://localhost:5672",
        Username: "artemis",
        Password: "artemis",
        Topology: createOnResolve{},
    }, amqp.Artemis{})
    if err != nil {
        log.Fatal(err)
    }

    bus, err := messaging.New(backend, messaging.Settings{
        Subscriptions: []messaging.SubscriptionSpec{{
            Name:        "greeter",
            Pattern:     "a.greeting.>",
            Shape:       messaging.Fanout,
            Mode:        messaging.AtLeastOnce,
            MaxDeliver:  3,
            DurableName: "greeter",
            Handler: func(_ context.Context, d messaging.Delivery) error {
                fmt.Println("received", d.Subject, d.Event.ID, "attempt", d.Attempt)

                return d.Ack()
            },
        }},
    })
    if err != nil {
        log.Fatal(err)
    }

    if err := bus.Start(ctx); err != nil {
        log.Fatal(err)
    }
    defer func() { _ = bus.Stop(context.Background()) }()

    select {
    case <-bus.Ready():
    case <-time.After(30 * time.Second):
        log.Fatal("the bus did not become ready")
    }

    err = bus.Publish(ctx, "a.greeting.en", envelope.Event{
        SpecVersion: "1.0", ID: "greeting-1", Source: "urn:example:tutorial",
        Type: "com.example.greeting.v1", Data: []byte(`{"text":"hello"}`),
    })
    if err != nil {
        log.Fatal(err)
    }

    time.Sleep(2 * time.Second)
}

amqp.New connects once, to read what the broker is configured to guarantee, and closes that connection. A wrong URL or wrong password fails here, not at bus.Start.

3. Run it

$ go run .
received a.greeting.en greeting-1 attempt 1

The subscription's Pattern, a.greeting.>, became the address a.greeting.# on the broker, and the queue greeter was created on it as a durable multicast queue. Attempt is 1 because the broker's delivery count was 0.

4. Publish the same event again

Run it a second time without changing the event.

$ go run .

Nothing is printed, and Publish returned no error. The adapter keys Artemis's duplicate-id cache with a hash of the event's Source and ID, so the broker accepted the second publish and kept nobody a copy. Change ID to "greeting-2" and run it again and the message arrives. The cache survives a broker restart. See Wire format.

5. Decline a message until it runs out

Change the handler to return d.Nack(), set MaxDeliver: 2, and use a new ID, "dlq-1". Run it.

$ go run .
received a.greeting.en dlq-1 attempt 1
received a.greeting.en dlq-1 attempt 2

There is no attempt 3. On the second decline the adapter rejected the message instead of handing it back, and the broker moved it to the address's dead-letter address. The queue DLQ now holds it, with its cloudEvents_id application property intact. Any AMQP client that attaches a receiver to the address DLQ will read it.

MaxDeliver of 2 is under the address's budget of 10, which is required: the adapter refuses a subscription whose MaxDeliver the broker's budget would cut short. See Topology it expects.

6. Clean up

$ docker stop artemis

The container was started with --rm, so it and its queues are gone.

What you have

A bus on Artemis with a durable queue, at-least-once delivery, and a dead-letter path. Next: how delivery and settlement work, and what the broker must be configured with.