【问题标题】:How to publish a message to pubsub emulator using C#如何使用 C# 将消息发布到 pubsub 模拟器
【发布时间】:2020-08-25 22:40:30
【问题描述】:

我设法创建了一个 c# 工具来将消息推送到谷歌云 pubsub。我似乎无法在任何地方找到如何将消息发布到模拟器。根据我的阅读内容,以下内容应该通过将端点传递给 ClientCreationSettings 来工作。但是我从模拟器收到了错误的请求响应...

public static async Task PublishMessage()
    {
        var endpoint = new ServiceEndpoint("localhost", 8085);
        ClientCreationSettings clientSettings = new ClientCreationSettings(1, null, null, endpoint);

        string message = "hello world";

        publisherClient = await PublisherClient.CreateAsync(new TopicName("project1", "topic1"), clientSettings);
        await publisherClient.PublishAsync(message);
        await publisherClient.ShutdownAsync(TimeSpan.FromSeconds(15));
    }

任何见解表示赞赏

【问题讨论】:

  • 您是否有从模拟器返回的实际错误消息?另外,您能否验证您在创建主题时是否设置了环境变量? cloud.google.com/pubsub/docs/…

标签: c# emulation google-cloud-pubsub


【解决方案1】:

对于 C#,在使用 gcloud beta emulators pubsub start --project=PUBSUB_PROJECT_ID [options] 启动模拟器并使用方便的 CLI 为 PUBSUB_EMULATOR_HOST 设置环境变量后,如 here 所示,您需要更新您的应用程序代码,如 sample 所示:

        string emulatorHostAndPort = Environment.GetEnvironmentVariable("PUBSUB_EMULATOR_HOST");

        PublisherServiceApiClient client = new PublisherServiceApiClientBuilder
        {
            Endpoint = emulatorHostAndPort,
            ChannelCredentials = ChannelCredentials.Insecure
        }.Build();
        // do things using client..

【讨论】:

    【解决方案2】:

    您需要发送 PubSubMessage 对象而不是字符串。

    var message = new PubsubMessage(){ Data = "hello world" };
    

    你的代码应该是这样的:

    public static async Task PublishMessage()
    {
        var clientSettings = new PublisherClient.ClientCreationSettings(
                    null,
                    PublisherServiceApiSettings.GetDefault(),
                    ChannelCredentials.Insecure,
                    "localhost:8085");
        
        var message = new PubsubMessage(){ Data = "hello world" };
    
        publisherClient = await PublisherClient.CreateAsync(new TopicName("project1", "topic1"), clientSettings);
        await publisherClient.PublishAsync(message};
        await publisherClient.ShutdownAsync(TimeSpan.FromSeconds(15));
    }
    

    来源:https://googleapis.github.io/google-cloud-dotnet/docs/Google.Cloud.PubSub.V1/

    【讨论】:

      猜你喜欢
      • 2021-12-13
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 2020-04-22
      • 1970-01-01
      • 2021-03-15
      • 2014-12-26
      相关资源
      最近更新 更多