Google PubSub仿真器是否与Google Cloud Pub / Sub API客户端库配合使用?

时间:2017-02-01 20:57:07

标签: google-app-engine google-cloud-pubsub

我们的Java应用程序在Google App Engine上运行。它正在使用Google的PubSub发布和使用消息。

Google PubSub有两个Java客户端。建议使用gRPC客户端,但如本页底部所述,Google App Engine不支持https://cloud.google.com/pubsub/grpc-overview

另一个库是Google Cloud Pub / Sub API客户端 - https://developers.google.com/api-client-library/java/apis/pubsub/v1

使用gRPC客户端lib时,很容易使用pubsub模拟器。只需设置一个环境属性即可。

PubSub API客户端是否可以与Google PubSub模拟器配合使用?

我们在本地运行应用程序时的目标是能够使用PubSub模拟器而不是连接到云中的实时实例。

2 个答案:

答案 0 :(得分:3)

This works but the PubSub client needs to be configured correctly against the port the emulator is using.

This is the code I use to create the PubSub client. It is based on PubSub Sample。注意setRootUrl部分。

private Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory) {
    Preconditions.checkNotNull(httpTransport);
    Preconditions.checkNotNull(jsonFactory);
    GoogleCredential credential = null;
    try {
        credential = GoogleCredential.getApplicationDefault();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(PubsubScopes.all());
    }
    // Please use custom HttpRequestInitializer for automatic
    // retry upon failures.
    HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
    Pubsub.Builder pubsubBuilder = new Pubsub.Builder(httpTransport, jsonFactory, initializer);
    pubsubBuilder.setApplicationName("<your project id>");
    //Check if this is localhost
    if (SystemProperty.environment.value() != SystemProperty.Environment.Value.Production) {
        pubsubBuilder.setRootUrl("http://localhost:8321/");
    }
    return pubsubBuilder.build();
}

然后使用以下命令启动模拟器:

gcloud beta模拟器pubsub start --host-port = localhost:8321

实际端口号并不重要。当然,每次重新启动模拟器时,都需要通过代码配置主题和订阅。

答案 1 :(得分:1)

我能够将Java API lib连接到模拟器。 我启动模拟器后: gcloud beta模拟器pubsub启动

我导出了它的地址: export PUBSUB_EMULATOR_HOST = localhost:EMULATOR_PORT