Google Pubsub
Since Camel 2.19
Both producer and consumer are supported
The Google Pubsub component provides access to Cloud Pub/Sub Infrastructure via the Google Cloud Java Client for Google Cloud Pub/Sub.
Maven users will need to add the following dependency to their pom.xml for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-google-pubsub</artifactId>
<!-- use the same version as your Camel core version -->
<version>x.x.x</version>
</dependency> URI Format
The Google Pubsub Component uses the following URI format:
google-pubsub://project-id:destinationName?[options]
Destination Name can be either a topic or a subscription name.
Configuring Options
Camel components are configured on two separate levels:
-
component level
-
endpoint level
Configuring Component Options
At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.
For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.
Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.
You can configure components using:
-
the Component DSL.
-
in a configuration file (
application.properties,*.yamlfiles, etc). -
directly in the Java code.
Configuring Endpoint Options
You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.
Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.
A good practice when configuring options is to use Property Placeholders.
Property placeholders provide a few benefits:
-
They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
-
They allow externalizing the configuration from the code.
-
They help the code to become more flexible and reusable.
The following two sections list all the options, firstly for the component followed by the endpoint.
Component Options
The Google Pubsub component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Whether to send credentials to Pub/Sub. Set it to false to connect without credentials, as the Pub/Sub emulator expects. The endpoints use this value unless they set their own. | true | boolean | |
The host and port of a local Pub/Sub emulator, such as localhost:8085. When set, the endpoints of the component connect to the emulator over a plain-text gRPC connection instead of to Google Cloud. Usually set together with authenticate=false. | String | ||
The service account key (JSON key file) to use as credentials for the publisher and the subscriber. It is loaded from the classpath by default, but you can prefix it with classpath:, file:, or http: to load the resource from different systems. When not set, the Application Default Credentials are used. The endpoints use this value unless they set their own. | String | ||
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
A comma-separated list of status codes (names of com.google.api.gax.rpc.StatusCode.Code, such as DEADLINE_EXCEEDED) that the pull requests of synchronousPull also retry. The Pub/Sub client library already retries UNKNOWN, ABORTED, UNAVAILABLE and INTERNAL. | String | ||
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
The maximum number of producers to cache. This could be increased if you have producers for lots of different topics. | int | ||
How many milliseconds each producer stays alive in the cache. | int | ||
Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | |
How many milliseconds a producer is allowed to take to terminate. | int | ||
To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message. | HeaderFilterStrategy |
Endpoint Options
The Google Pubsub endpoint is configured using URI syntax:
google-pubsub:projectId:destinationName
With the following path and query parameters:
Path Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Required The ID of the Google Cloud project of the topic or subscription. | String | ||
Required The name of the topic for the producer, or of the subscription for the consumer. It is the short name, such as my-topic or my-subscription, not the full resource name that starts with projects/. | String |
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
How the consumer acknowledges the messages it receives. AUTO acknowledges (acks) a message when its exchange completes, and negatively acknowledges (nacks) it when the exchange fails. NONE leaves it to the route, which calls ack or nack on the GooglePubsubAcknowledge in the CamelGooglePubsubAcknowledge header. Enum values:
| AUTO | AckMode | |
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
The number of subscribers that get messages from the subscription in parallel. Each one opens its own streaming pull, or with synchronousPull, sends its own pull requests. | 1 | Integer | |
To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | ExceptionHandler | ||
Sets the exchange pattern when the consumer creates an exchange. Enum values:
| ExchangePattern | ||
The maximum period, in seconds, for which the subscriber extends the ack deadline of a message that is not acknowledged yet. After it, Pub/Sub may deliver the message again. 0 disables the extension, and a negative value is rejected. Not used with synchronousPull. | 3600 | int | |
The maximum number of delivery attempts for each message. When set to a positive value, the consumer will automatically nack any message whose delivery attempt count is greater than or equal to this value, allowing Pub/Sub to route it to the dead-letter topic without processing it. This prevents infinite redelivery loops when short retry delays are configured. If not explicitly set and the subscription has a dead-letter policy, the value is automatically fetched from the subscription configuration at consumer startup. Set to 0 to disable enforcement. | 0 | int | |
The maximum number of messages that a pull request returns (Pub/Sub may return fewer). Must be a positive number. Only used with synchronousPull. | 1 | Integer | |
Whether to get the messages with pull requests of up to maxMessagesPerPoll messages each, instead of with the streaming pull of the asynchronous subscriber. The synchronous pull does not extend the ack deadline of the messages. | false | boolean | |
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
Whether the publisher publishes the messages that have the same ordering key (the CamelGooglePubsubOrderingKey header) in order. When disabled, publishing a message with an ordering key fails. The subscription must have message ordering enabled to deliver them in order. | false | boolean | |
The Pub/Sub service endpoint that the producer publishes to, as host:port, such as the regional endpoint us-east1-pubsub.googleapis.com:443. With messageOrderingEnabled, set it to a regional endpoint, as Pub/Sub keeps the order only of the messages published to the same region; a warning is logged when it is not set. When not set, the global endpoint of the Pub/Sub client library is used. | String | ||
The RetrySettings (com.google.api.gax.retrying.RetrySettings) of the publisher, which control how it retries a publish request that failed with a retryable error. When not set, the default retry settings of the Pub/Sub client library are used. | RetrySettings | ||
Autowired A custom GooglePubsubSerializer to use for serializing message payloads in the producer. It is used only for a body that is not a String or a byte array and that the type converter cannot convert to a byte array. By default, Java serialization is used. | GooglePubsubSerializer | ||
To use a custom HeaderFilterStrategy to filter headers to and from Camel message. | HeaderFilterStrategy | ||
Whether to include all Google headers when mapping between the Pub/Sub message attributes and the Camel message headers. Setting this to true includes properties such as x-goog. Not used when a custom headerFilterStrategy is set. | false | boolean | |
Deprecated The name of the logger that the endpoint, the producer and the consumer log with, instead of their class names. | String | ||
Whether to send credentials to Pub/Sub. Set it to false to connect without credentials, as the Pub/Sub emulator expects. | true | boolean | |
The service account key (JSON key file) to use as credentials for the publisher and the subscriber. It is loaded from the classpath by default, but you can prefix it with classpath:, file:, or http: to load the resource from different systems. When not set, the Application Default Credentials are used. | String |
Message Headers
The Google Pubsub component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelGooglePubsubMessageId (common) Constant: | The ID of the message, assigned by the server when the message is published. | String | |
CamelGooglePubsubMsgAckId (consumer) Constant: | The ID used to acknowledge the received message. Only set with synchronousPull. | String | |
CamelGooglePubsubSubscriptionName (consumer) Constant: | The name of the subscription the message was received from. | String | |
CamelGooglePubsubPublishTime (consumer) Constant: | The time at which the message was published. | Timestamp | |
CamelGooglePubsubAttributes (common) Constant: | Deprecated The attributes of the message, as a map. Deprecated: the consumer also sets each attribute as a header, and the producer sends the headers as attributes. | Map | |
CamelGooglePubsubOrderingKey (producer) Constant: | The ordering key of the message to publish. Messages with the same ordering key are delivered in the order they are published. Requires messageOrderingEnabled=true. | String | |
CamelGooglePubsubAcknowledge (consumer) Constant: | The GooglePubsubAcknowledge to acknowledge (ack) or negatively acknowledge (nack) the message with, when ackMode=NONE. | GooglePubsubAcknowledge | |
CamelGooglePubsubDeliveryAttempt (consumer) Constant: | The delivery attempt counter received from PubSub. This is the approximate number of times the message has been delivered. This will be 1 for the first delivery. This feature requires a dead-letter policy to be configured on the subscription. | Integer |
Message Body
The message body at each side of the Google Pubsub component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.
| Side | Body | Description |
|---|---|---|
Consumer |
| The data of the Pub/Sub message as a byte array, with its attributes in headers: convert or unmarshal it. |
Producer input |
| Text is sent as UTF-8 and bytes as they are; a List of the exchanges of a grouped aggregation is sent as one message per exchange. A body that converts to bytes, such as a stream or a file, is sent as its content. Any other body goes to the serializer, by default Java serialization, so a Map or a POJO is sent as Java-serialized bytes: marshal it first. No body fails. Not known when |
Producer output |
| Unchanged, with the id of the published message in a header. |
The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.
Deterministic simulation tests
The consumer of the Google Pubsub component is tested with deterministic simulation tests: the real consumer runs under a seeded virtual-time scheduler against a fake of the external system, which injects faults while the tests check invariants. A failing seed can be replayed. These are the fake worlds of the component:
| World | What it checks | Issues |
|---|---|---|
Fake: FakePubsub: a subscription (Pull, Acknowledge, ModifyAckDeadline, ack deadlines, dead letter policy) behind the SubscriberStub of synchronousPull Tests: | Covers:
Faults:
Invariants:
|
The worlds and their tests are in the test sources of the component. How to run them, replay a seed and write a world is described in Running the tests and Writing a fake world.
Usage
Producer Endpoints
Producer endpoints can accept and deliver to PubSub individual and grouped exchanges alike. Grouped exchanges have Exchange.GROUPED_EXCHANGE property set.
Google PubSub expects the payload to be byte[] array, Producer endpoints will send, in this order:
-
String body as
byte[]encoded as UTF-8 -
byte[]body as is -
any other body that the Camel type converter can convert to
byte[], as the result of that conversion. This sends the content of a stream, a stream cache, ajava.io.File, ajava.nio.file.Pathor the file of the File consumer, sofrom("file:inbox").to("google-pubsub:project:topic")publishes the content of each file. -
everything else is passed to the
serializer, which by default uses Java serialization (ObjectOutputStream), so for example aMapor a POJO is sent as Java-serialized bytes. Set a customserializerto send such bodies in another format, or marshal the body (for example to JSON) before the producer.
A message without a body is not sent: the producer fails with an InvalidPayloadException.
A Map set as message header GooglePubsubConstants.ATTRIBUTES will be sent as PubSub attributes.
Google PubSub supports ordered message delivery.
To enable this, set the options messageOrderingEnabled to true, and the pubsubEndpoint to a regional endpoint, such as us-east1-pubsub.googleapis.com:443.
When producing messages set the message header GooglePubsubConstants.ORDERING_KEY . This will be set as the PubSub orderingKey for the message.
For more information, see Ordering messages.
Once exchange has been delivered to PubSub the PubSub Message ID will be assigned to the header GooglePubsubConstants.MESSAGE_ID.
Consumer Endpoints
Google PubSub will redeliver the message if it has not been acknowledged within the time period set as a configuration option on the subscription.
The component will acknowledge the message once exchange processing has been completed.
If the route throws an exception, the exchange is marked as failed, and the component will NACK the message. It will be redelivered immediately.
The component acks or nacks the message it received, also when the route changed or removed the GooglePubsubConstants.ACK_ID header (the Acknowledgement ID of the message), or replaced the message. With manual acknowledgement and the synchronous consumer, the Acknowledgement IDs are taken from the exchange given to ack or nack (see Manual Acknowledgement).
When the consumer cannot get messages (Pub/Sub cannot be reached, a missing permission or subscription, credentials that cannot be loaded), it logs the failure (the first one in a row at ERROR, the next ones in one WARN line), gives it to the exception handler (with bridgeErrorHandler=true, to the error handler of the route), and subscribes or pulls again every 5 seconds until the cause is gone. Meanwhile, with the consumer health checks of Camel enabled, the readiness check of the consumer of the route (consumer:<routeId>) is DOWN with the failure.
Delivery Attempts and Dead Letter Queues
When a subscription has a dead-letter policy configured, the component exposes the delivery attempt count via the header GooglePubsubConstants.DELIVERY_ATTEMPT. This header contains an Integer representing the approximate number of times the message has been delivered. The first delivery will have a value of 1.
| The delivery attempt header is only available when the subscription has a dead-letter policy configured. Without a dead-letter policy, the header will not be set. |
This allows routes to implement custom retry logic based on the delivery attempt count:
from("google-pubsub:{{project.name}}:{{subscription.name}}")
.process(exchange -> {
Integer deliveryAttempt = exchange.getIn().getHeader(GooglePubsubConstants.DELIVERY_ATTEMPT, Integer.class);
if (deliveryAttempt != null && deliveryAttempt > 3) {
// Custom handling for messages that have been redelivered multiple times
log.warn("Message has been delivered {} times", deliveryAttempt);
}
// Process the message
}); With a dead-letter policy, after the configured maximum delivery attempts are exceeded, the message will automatically be forwarded to the dead-letter topic by Google PubSub.
Automatic Max Delivery Attempts Enforcement
The component can enforce the subscription’s maxDeliveryAttempts setting at the consumer level. When enabled, messages whose delivery attempt count is greater than or equal to the configured maximum will be automatically nacked without processing, allowing Pub/Sub to route them to the dead-letter topic. This prevents infinite redelivery loops that can occur with short retry delays.
The maxDeliveryAttempts value is resolved as follows:
-
If explicitly set via the endpoint option, that value is used.
-
If not explicitly set, the component attempts to auto-fetch the value from the subscription’s dead-letter policy at consumer startup.
-
If auto-fetch fails (e.g., insufficient permissions or no dead-letter policy), enforcement is disabled and a warning is logged.
-
A value of
0disables enforcement.
-
Java
-
XML
-
YAML
from("google-pubsub:{{project.name}}:{{subscription.name}}?maxDeliveryAttempts=5")
.to("direct:process"); <route>
<from uri="google-pubsub:{{project.name}}:{{subscription.name}}?maxDeliveryAttempts=5"/>
<to uri="direct:process"/>
</route> - route:
from:
uri: google-pubsub:{{project.name}}:{{subscription.name}}
parameters:
maxDeliveryAttempts: 5
steps:
- to:
uri: direct:process Message Body
The consumer endpoint returns the content of the message as byte[]. Exactly as the underlying system sends it. It is up for the route to convert/unmarshall the contents.
Authentication Configuration
By default, this component acquires credentials using GoogleCredentials.getApplicationDefault(). This behavior can be disabled by setting authenticate option to false, in which case requests to Google API will be made without authentication details. This is only desirable when developing against an emulator. This behavior can be altered by supplying a path to a service account key file.
Workload Identity on GKE and other Google-managed environments
Because the default is Application Default Credentials, a workload that already carries a Google identity needs no credential configuration at all: leave serviceAccountKey unset and ADC resolves the identity attached to the workload. On GKE with Workload Identity that is the GCP service account bound to the pod’s Kubernetes service account; the same applies on Compute Engine and Cloud Run.
// on GKE with Workload Identity, Compute Engine or Cloud Run: nothing to configure
from("google-pubsub:my-project:my-subscription")
.to("direct:process"); | Configuring Workload Identity Federation for an external identity provider (an explicit WIF credential configuration file for AWS, Azure or GitHub Actions), or service account impersonation, is not exposed as an endpoint option by the Google components. |
Manual Acknowledgement
By default, the PubSub consumer will acknowledge messages once the exchange has been processed, or negative-acknowledge them if the exchange has failed.
If the ackMode option is set to NONE, the component will not acknowledge messages, and it is up to the route to do so. In this case, a GooglePubsubAcknowledge object is stored in the header GooglePubsubConstants.GOOGLE_PUBSUB_ACKNOWLEDGE and can be used to acknowledge messages:
from("google-pubsub:{{project.name}}:{{subscription.name}}?ackMode=NONE")
.process(exchange -> {
GooglePubsubAcknowledge acknowledge = exchange.getIn().getHeader(GooglePubsubConstants.GOOGLE_PUBSUB_ACKNOWLEDGE, GooglePubsubAcknowledge.class);
acknowledge.ack(exchange); // or .nack(exchange)
}); Manual acknowledgement works with both the asynchronous and synchronous consumers. The synchronous consumer (synchronousPull=true) uses the acknowledgement id stored in the header GooglePubsubConstants.ACK_ID of the exchange given to ack or nack. The asynchronous consumer acknowledges the message the GooglePubsubAcknowledge object was taken from, whatever the exchange given.
With the synchronous consumer, ack or nack of an aggregated exchange whose body is a List<Exchange>, such as the result of the GroupedExchangeAggregationStrategy, applies to every grouped message, in one request:
from("google-pubsub:{{project.name}}:{{subscription.name}}?synchronousPull=true&ackMode=NONE&maxMessagesPerPoll=10")
.aggregate(constant(true), new GroupedExchangeAggregationStrategy()).completionSize(10)
.process(exchange -> {
List<Exchange> grouped = exchange.getIn().getBody(List.class);
GooglePubsubAcknowledge acknowledge = grouped.get(0).getIn().getHeader(GooglePubsubConstants.GOOGLE_PUBSUB_ACKNOWLEDGE, GooglePubsubAcknowledge.class);
acknowledge.ack(exchange); // acknowledges the 10 grouped messages
}); The request goes to the subscription of the GooglePubsubAcknowledge used, so every grouped exchange must come from that same subscription, that is from the same consumer endpoint. The synchronous consumer does not extend the ack deadline of the messages it pulls, so the aggregated exchange must be acknowledged before the ack deadline of the subscription expires, otherwise the grouped messages are delivered again. With the asynchronous consumer, acknowledge each grouped exchange with its own GooglePubsubAcknowledge header.