Search code examples
google-cloud-functionsspring-cloudspring-cloud-function

How to get the metadata of Pub/Sub event in Spring Cloud function on Google Cloud Function


I have created a simple Google Cloud Function with Spring Cloud Function library to get triggered on the arrival of the Pub/Sub message. I followed the sample function-sample-gcp-background. Whenever a message is triggered to the Pub/Sub, it gets printed from the Cloud Function as expected.

But I wonder how can I get the metadata of the Pub/Sub message in the Cloud Functon. The Google Cloud Function documentation says that

This metadata is accessible via the context object that is passed to your function when it is invoked.

How can I access this metadata (or the context object) in a Spring Cloud Function application?

UPDATE :- Version spring-cloud-function-adapter-gcp:3.1.2

UPDATE 2:- I raised an issue in github and got the issue resolved. Thanks to Spring Cloud Function team.


Solution

  • Got the issue resolved as per the advice from spring-cloud-function team. The Consumer function needs to accept the parameter of type Message<PubSubMessage> instead of PubSubMessage to get the Context object.

        @Bean
        public Consumer<Message<PubSubMessage>> pubSubFunction() {
            return message -> {
                // The PubSubMessage data field arrives as a base-64 encoded string and must be decoded.
                // See: https://cloud.google.com/functions/docs/calling/pubsub#event_structure
    
                PubSubMessage payload = message.getPayload();
                String decodedMessage = new String(
                        Base64.getDecoder().decode(message.getPayload().getData()), StandardCharsets.UTF_8);
                System.out.println("Hello!!! Received Pub/Sub message with data: " + decodedMessage);
    
                            // Print out timestamp and event id
                Context ctx = message.getHeaders().get("gcf_context", Context.class);
                System.out.println(ctx.eventId());
                System.out.println(ctx.timestamp());
            };
        }
    

    Ref :- github issue #695