如何在 Google Cloud Function 上的 Spring Cloud Function 中获取 Pub/Sub 事件的元数据

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

我使用 Spring 云函数库创建了一个简单的 Google 云函数,以便在 Pub/Sub 消息到达时触发。我跟着样本 function-sample-gcp-background。每当消息被触发到 Pub/Sub 时,它就会按预期从 Cloud Function 中打印出来。

但我想知道如何在 Cloud Functon 中获取 Pub/Sub 消息的元数据。 Google Cloud Function documentation 表示

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

如何在 Spring Cloud Function 应用程序中访问此元数据(或上下文对象)?

更新:-版本spring-cloud-function-adapter-gcp:3.1.2

更新 2:- 我在 github 中提出了一个问题并解决了这个问题。感谢 Spring Cloud Function 团队。

当您使用后台功能时,PubSub 消息和上下文将被提取并在 PubSub 消息中提供。如果您查看 PubSub 对象 here;您在其中嵌入了发布时间和消息 ID。您只需使用它们!

根据 spring-cloud-function 团队的建议解决了问题。 Consumer函数需要接受类型为Message<PubSubMessage>的参数而不是PubSubMessage来获取Context对象。

    @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());
        };
    }

参考:- github issue #695