使用Java中的Google Cloud PubSub模拟器

时间:2016-01-27 14:17:11

标签: java google-cloud-platform google-cloud-pubsub

我设置Pubsub.Builder,根网址指向本地PubSub模拟器(我的情况为localhost:8036)。它似乎工作,我看到模拟器正在接收我的测试推送,但给我错误400错误请求。

发布代码:

auth = GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
         .createScoped(PubsubScopes.all());
client = new Pubsub.Builder(HTTP_TRANSPORT, JSON_FACTORY, auth)
         .setApplicationName "test"
         .setRootUrl("http://localhost:8036/")
         .build();
msg = new PubsubMessage().encodeData("{\"a\": 1, \"b\": 2}".getBytes());
req = new PublishRequest().setMessages(Arrays.asList(msg));
client.projects()
  .topics()
  .publish("projects/GCLOUD-DEFAULT-PROJECT/topics/test-topic", req)
  .execute();

在模拟器控制台输出中,我看到以下(非常基本的PublishRequest):

[pubsub] jan 27, 2016 9:03:20 PM com.google.cloud.pubsub.testing.v1.FakePubsubGrpcServer$2 operationComplete
[pubsub] INFO: Adding handler(s) to newly registered Channel.
[pubsub] jan 27, 2016 9:03:20 PM com.google.cloud.pubsub.testing.v1.NettyUtil$HttpVersionDecider channelRead
[pubsub] INFO: Detected non-HTTP/2 connection.
[pubsub] jan 27, 2016 9:03:20 PM com.google.cloud.pubsub.testing.v1.NettyUtil$HttpJsonAdapter channelRead
[pubsub] INFO: Invalid input: Expect message object but got: "\u001f�\b\u0000\u0000\u0000\u0000\u0000\u0000\u0000�V�M-.NLO-V���VJI"
[pubsub] com.google.protobuf.InvalidProtocolBufferException: Expect message object but got: "\u001f�\b\u0000\u0000\u0000\u0000\u0000\u0000\u0000�V�M-.NLO-V���VJI"
[pubsub]    at com.google.protobuf.util.JsonFormat$ParserImpl.mergeMessage(JsonFormat.java:1099)
[pubsub]    at com.google.protobuf.util.JsonFormat$ParserImpl.merge(JsonFormat.java:1075)
[pubsub]    at com.google.protobuf.util.JsonFormat$ParserImpl.merge(JsonFormat.java:973)
[pubsub]    at com.google.protobuf.util.JsonFormat$Parser.merge(JsonFormat.java:201)
[pubsub]    at com.google.cloud.pubsub.testing.v1.PubsubJsonGrpcAdapters$PublisherAdapter.handleRequest(PubsubJsonGrpcAdapters.java:231)
[pubsub]    at com.google.cloud.pubsub.testing.v1.NettyUtil$HttpJsonAdapter.channelRead(NettyUtil.java:94)
[pubsub]    at io.netty.channel.ChannelHandlerInvokerUtil.invokeChannelReadNow(ChannelHandlerInvokerUtil.java:83)

似乎默认的PubSub客户端使用不同的协议,但我没有看到任何配置它的方法。

如何将com.google.apis:google-api-services-pubsub库与本地模拟器一起使用?

1 个答案:

答案 0 :(得分:2)

模拟器不需要或处理身份验证或授权;我猜测问题出在哪里。您可以尝试将null作为最后一个参数传递给构建器吗?

此外,似乎必须明确禁用Gzip压缩。请在构建器上设置:

.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
  @Override
  public void initialize(AbstractGoogleClientRequest<?> request) throws IOException {
    request.setDisableGZipContent(true);
  }
})