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

问题描述

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

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

可以通过传递给的上下文对象访问此元数据 调用时的函数

如何在 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