Exemplo n.º 1
0
        public async Task SimpleOverview()
        {
            string projectId      = _fixture.ProjectId;
            string topicId        = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            // Sample: SimpleOverview
            // First create a topic.
            PublisherServiceApiClient publisherService = await PublisherServiceApiClient.CreateAsync();

            TopicName topicName = new TopicName(projectId, topicId);

            publisherService.CreateTopic(topicName);

            // Subscribe to the topic.
            SubscriberServiceApiClient subscriberService = await SubscriberServiceApiClient.CreateAsync();

            SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);

            subscriberService.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60);

            // Publish a message to the topic using PublisherClient.
            PublisherClient publisher = await PublisherClient.CreateAsync(topicName);

            // PublishAsync() has various overloads. Here we're using the string overload.
            string messageId = await publisher.PublishAsync("Hello, Pubsub");

            // PublisherClient instance should be shutdown after use.
            // The TimeSpan specifies for how long to attempt to publish locally queued messages.
            await publisher.ShutdownAsync(TimeSpan.FromSeconds(15));

            // Pull messages from the subscription using SimpleSubscriber.
            SubscriberClient subscriber = await SubscriberClient.CreateAsync(subscriptionName);

            List <PubsubMessage> receivedMessages = new List <PubsubMessage>();
            // Start the subscriber listening for messages.
            await subscriber.StartAsync((msg, cancellationToken) =>
            {
                receivedMessages.Add(msg);
                Console.WriteLine($"Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}");
                Console.WriteLine($"Text: '{msg.Data.ToStringUtf8()}'");
                // Stop this subscriber after one message is received.
                // This is non-blocking, and the returned Task may be awaited.
                subscriber.StopAsync(TimeSpan.FromSeconds(15));
                // Return Reply.Ack to indicate this message has been handled.
                return(Task.FromResult(SubscriberClient.Reply.Ack));
            });

            // Tidy up by deleting the subscription and the topic.
            subscriberService.DeleteSubscription(subscriptionName);
            publisherService.DeleteTopic(topicName);
            // End sample

            Assert.Equal(1, receivedMessages.Count);
            Assert.Equal("Hello, Pubsub", receivedMessages[0].Data.ToStringUtf8());
        }
Exemplo n.º 2
0
        private async Task <string> PublishAsync <T>(TopicName topicName, string emulatorHostAndPort, T message)
        {
            PublisherClient publisher = await PublisherClient.CreateAsync(topicName,
                                                                          new PublisherClient.ClientCreationSettings(null, null, ChannelCredentials.Insecure, emulatorHostAndPort));

            // PublishAsync() has various overloads. Here we're using the string overload.
            string messageId = await publisher.PublishAsync(serializer(message), System.Text.Encoding.UTF8);

            // PublisherClient instance should be shutdown after use.
            // The TimeSpan specifies for how long to attempt to publish locally queued messages.
            await publisher.ShutdownAsync(TimeSpan.FromSeconds(15)); //?

            return(messageId);
        }
Exemplo n.º 3
0
        public async Task Write(string eventData, HttpContext context)
        {
            PublisherClient publisher = null;

            foreach (var topicId in _topicIds)
            {
                var topicName = new TopicName(_projectId, topicId);
                _logger.LogInformation($"Publishing to topic '{topicId}' with data '{eventData}");
                publisher = await PublisherClient.CreateAsync(topicName);

                await publisher.PublishAsync(eventData);
            }

            if (publisher != null)
            {
                await publisher.ShutdownAsync(TimeSpan.FromSeconds(10));
            }
        }
        public async Task Write(object eventData, HttpContext context)
        {
            PublisherClient publisher = null;

            foreach (var topicId in _topicIds)
            {
                var topicName = new TopicName(_projectId, topicId);
                publisher = await PublisherClient.CreateAsync(topicName);

                var message = JsonConvert.SerializeObject(eventData);
                _logger.LogInformation($"Publishing to topic '{topicId}' with message '{message}'");
                await publisher.PublishAsync(message);
            }

            if (publisher != null)
            {
                await publisher.ShutdownAsync(TimeSpan.FromSeconds(10));
            }
        }
Exemplo n.º 5
0
        public async Task ShutdownPublisherAsync(string topic, CancellationToken hardStopToken)
        {
            PublisherClient client = await TryGetPublisherClient(topic);

            await client.ShutdownAsync(hardStopToken);
        }
    public async Task WithEmulatorAsync(string projectId, string topicId, string subscriptionId)
    {
        // Use EmulatorDetection.EmulatorOrProduction to create service clients that will
        // that will connect to the PubSub emulator if the PUBSUB_EMULATOR_HOST environment
        // variable is set, but will otherwise connect to the production environment.

        // Create the PublisherServiceApiClient using the PublisherServiceApiClientBuilder
        // and setting the EmulatorDection property.
        PublisherServiceApiClient publisherService = await new PublisherServiceApiClientBuilder
        {
            EmulatorDetection = EmulatorDetection.EmulatorOrProduction
        }.BuildAsync();

        // Use the client as you'd normally do, to create a topic in this example.
        TopicName topicName = new TopicName(projectId, topicId);

        publisherService.CreateTopic(topicName);

        // Create the SubscriberServiceApiClient using the SubscriberServiceApiClientBuilder
        // and setting the EmulatorDection property.
        SubscriberServiceApiClient subscriberService = await new SubscriberServiceApiClientBuilder
        {
            EmulatorDetection = EmulatorDetection.EmulatorOrProduction
        }.BuildAsync();

        // Use the client as you'd normally do, to create a subscription in this example.
        SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);

        subscriberService.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60);

        // Create the PublisherClient using PublisherClient.ClientCreationSettings
        // and call the WithEmulatorDection method.
        PublisherClient publisher = await PublisherClient.CreateAsync(
            topicName,
            new PublisherClient.ClientCreationSettings()
            .WithEmulatorDetection(EmulatorDetection.EmulatorOrProduction));

        // Use the client as you'd normally do, to send a message in this example.
        await publisher.PublishAsync("Hello, Pubsub");

        await publisher.ShutdownAsync(TimeSpan.FromSeconds(15));

        // Create the SubscriberClient using SubscriberClient.ClientCreationSettings
        // and call the WithEmulatorDection method.
        SubscriberClient subscriber = await SubscriberClient.CreateAsync(
            subscriptionName,
            new SubscriberClient.ClientCreationSettings()
            .WithEmulatorDetection(EmulatorDetection.EmulatorOrProduction));

        List <PubsubMessage> receivedMessages = new List <PubsubMessage>();

        // Use the client as you'd normally do, to listen for messages in this example.
        await subscriber.StartAsync((msg, cancellationToken) =>
        {
            receivedMessages.Add(msg);
            Console.WriteLine($"Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}");
            Console.WriteLine($"Text: '{msg.Data.ToStringUtf8()}'");
            // In this example we stop the subscriber when the message is received.
            // You may leave the subscriber running, and it will continue to received published messages
            // if any.
            // This is non-blocking, and the returned Task may be awaited.
            subscriber.StopAsync(TimeSpan.FromSeconds(15));
            // Return Reply.Ack to indicate this message has been handled.
            return(Task.FromResult(SubscriberClient.Reply.Ack));
        });
    }
Exemplo n.º 7
0
 public void Dispose()
 {
     _logger.Debug("[GCPFanout.Dispose()] Delete topic: {_topicID}.", _topicID);
     _publisher.ShutdownAsync(TimeSpan.FromSeconds(15));
     _publisherService.DeleteTopic(_topicName);
 }