DataFlow SDK 2.x: PubSubIO 授权错误

DataFlow SDK 2.x: PubSubIO authorization error

Reading from Pubsub using Dataflow Java SDK 2

我正在尝试如下:

public class App2 {
    public static void main(String[] args) {
        Pipeline pipeline = Pipeline.create(PipelineOptionsFactory.fromArgs(args).create());
        pipeline
                .apply("ReadStrinsFromPubsub",
                        PubsubIO.readStrings().fromTopic("projects/dev/topics/trading"))
                .apply("PrintToStdout", ParDo.of(new DoFn<String, Void>() {
                    @ProcessElement
                    public void processElement(ProcessContext c) {
                        System.out.printf("Received at %s : %s\n", Instant.now(), c.element()); // debug log
                    }
                }));

        pipeline.run().waitUntilFinish();
    }
}

发生错误的原因是:

com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "The request is missing a valid API key.",
    "reason" : "forbidden"
  } ],
  "message" : "The request is missing a valid API key.",
  "status" : "PERMISSION_DENIED"
}

我该如何解决?

您可能缺少为本地计算机设置的用于访问 GCP 的服务帐户。

请参考 Getting Started with Authentication 设置您的服务帐户和 GOOGLE_APPLICATION_CREDENTIALS 变量。

1) 在 GCP 控制台中创建一个服务帐户;

2) 下载json密钥文件到本地;

3) 将 GOOGLE_APPLICATION_CREDENTIALS 变量设置为 json 密钥文件的路径。

gcloud auth application-default login 将使您能够使用登录计算机的默认服务帐户。