Java: PubsubMessage 订阅者收到没有数据或属性的消息

Java: PubsubMessage Subscriber receives message with no data or attribute

我正在尝试接收主题消息并在订阅者中接收消息。但是在订阅者中我没有收到任何消息,只有一个空的 PubsubMessage.

订阅者

package com.dsam.assignment02.functions;

import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import com.google.pubsub.v1.PubsubMessage;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;

public class OrderBillPdfGeneratorFunction implements BackgroundFunction<PubsubMessage> {
    private static final Logger logger = Logger.getLogger(OrderBillPdfGeneratorFunction.class.getName());

    @Override
    public void accept(PubsubMessage payload, Context context) throws Exception {
        String s = payload.getData().isEmpty() ? "No data" : new String(
            Base64.getDecoder().decode(payload.getData().toByteArray()),
            StandardCharsets.UTF_8
        );
        String t = String.valueOf(payload.getAttributesCount());
        logger.log(Level.INFO, String.format("Data: %s\nAttribute Count: %s", s, t));
    }
}

日志输出

Data: No data
Attribute Count: 0

知道我在这里遗漏了什么吗?

更新

我从云控制台pub/sub主题发布消息,但仍然没有收到任何数据,这排除了发布者代码问题的可能性。

最终我解决了这个问题。我必须为函数参数定义自己的 class 而不是使用 com.google.pubsub.v1.PubsubMessage.

定义如下 PubSubMessage class 并用作 public class OrderBillPdfGeneratorFunction implements BackgroundFunction<PubSubMessage>

public static class PubSubMessage {
    public String data;
    public Map<String, String> attributes;
    public String messageId;
    public String publishTime;
}

这解决了问题。

编辑

这是完整的工作代码。

package com.dsam.assignment02.functions;

import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import com.google.pubsub.v1.PubsubMessage;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;

public class OrderBillPdfGeneratorFunction implements BackgroundFunction<PubSubMessage> {
    private static final Logger logger = Logger.getLogger(OrderBillPdfGeneratorFunction.class.getName());

    @Override
    public void accept(PubSubMessage payload, Context context) throws Exception {
        String s = payload.getData().isEmpty() ? "No data" : new String(
            Base64.getDecoder().decode(payload.getData().toByteArray()),
            StandardCharsets.UTF_8
        );
        String t = String.valueOf(payload.getAttributesCount());
        logger.log(Level.INFO, String.format("Data: %s\nAttribute Count: %s", s, t));
    }

    public static class PubSubMessage {
        public String data;
        public Map<String, String> attributes;
        public String messageId;
        public String publishTime;
    }
}