Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Consuming PubSub Message via Push Subscription and Cloud Run

Hello Community,

I have the following scenario: We need to consume PubSub messages using a Push Subscription and a Cloud Run App.

We have a PubSub topic, a Push Subscription and a Cloud Run Service deployed in GCP. The flow between the PubSub and Cloud Run Service works fine, it is just I can not retrieve the message attributes.

This is the Rest Controller we are sing to process the POST Request:

@RestController
@RequestMapping("/business-unit")
public class GenericBusinessUnitController {
private final GCSLogger logger = GCSLoggerProvider.INSTANCE.getLogger();

@PostMapping
public HttpStatus consume(@RequestBody String requestBody) {
Preconditions.checkNotNull(requestBody);
logger.info(FlowId.BUSINESS_UNIT_CONSUMER.name(), "Request Body: " + requestBody);

return HttpStatus.PROCESSING;
}
}

When I publish a message (Plane String value: "Demo Message") and add an attribute (Date:05/11/2024) like this:

valentiniacov_0-1730826802505.png

I am able to see only the message body and not the attributes. Please see:

valentiniacov_1-1730827049944.png

 



Question: How the signature of the @PostMapping method on the @RestController should look like in order to be able to process both the message body and its attributes?

Also, after 50 seconds the Cloud Run throws this error:

valentiniacov_2-1730827141047.png

How can I prevent it?

Thank you for your help!



0 1 813
1 REPLY 1

Hi @valentiniacov,

It looks like you’ve got the Pub/Sub to Cloud Run setup working nicely, except for that tricky issue with the message attributes and the timeout error—let's sort those out!

To access the message attributes along with the message body, you’ll need to adjust the method signature in your controller. Instead of receiving a plain string, structure it to accept both the message and attributes from Pub/Sub as a JSON object. Here's a structured approach:

  1. Define a Wrapper Class: Create a PubSubMessage class for parsing both data and attributes.
  2. Update the Controller Method: Change the @PostMapping method to accept PubSubRequest and retrieve both the data and attributes from the request object.

Related timeout, consider increasing the timeout duration in Cloud Run settings to prevent it from timing out after 50 seconds. This can be done in Cloud Run > Service > Edit & Deploy New Revision > Advanced Settings.

Hope this helps!