Send message with an “ordering key” to GCP Pub/Sub via “Spring Integration”

To set an “ordering key” on a message sent to Google Pub/Sub via Spring Boot using “Spring Integration”, you need to do the following:

(1) Set the publisher as supporting ordering. Add the following to your application.yaml:

spring:
  cloud:
    gcp:
      pubsub:
        publisher:
          enable-message-ordering: true

(2) Set the ordering key on the message you’re sending:

var message = MessageBuilder
    .withPayload(request)
    .setHeaderIfAbsent(GcpPubSubHeaders.ORDERING_KEY, "my key")
    .build();

This works on Spring Boot 2.7.8 with Spring Integration 5.5.16 and the com.google.cloud:spring-cloud-gcp-pubsub dependency version 3.4.2.

P.S. I recently created a nerdy privacy-respecting tool called When Will I Run Out Of Money? It's available for free if you want to check it out.

This article is © Adrian Smith.
It was originally published on 7 Feb 2023
More on: Coding | Java | Spring