【问题标题】:Does the Google PubSub Emulator work with the Google Cloud Pub/Sub API Client Library?Google PubSub 模拟器是否可以与 Google Cloud Pub/Sub API 客户端库一起使用?
【发布时间】:2017-06-18 18:44:50
【问题描述】:

我们的 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 Client - https://developers.google.com/api-client-library/java/apis/pubsub/v1

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

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

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

【问题讨论】:

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


    【解决方案1】:

    这可行,但需要针对模拟器使用的端口正确配置 PubSub 客户端。

    这是我用来创建 PubSub 客户端的代码。它基于 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

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

    【讨论】:

    • 正是我想要的……在构建客户端并使用专用端口启动模拟器时在代码中设置它。
    【解决方案2】:

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

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

    【讨论】:

    • 我无法确认这一点,但您可能是对的,当从 Intellij 运行我们的 GAE 应用程序时,我不确定如何设置 PUBSUB_EMULATOR_HOST。 Google AppEngine Dev Server 的运行配置没有放置环境变量的地方。也许有一种我不知道的方法。
    猜你喜欢
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-12
    • 2021-02-21
    • 2018-08-09
    相关资源
    最近更新 更多