Exemple #1
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Pizza worker running at: {time}", DateTimeOffset.Now);
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    var msg = await PizzaOrdersQueue.GetMessageAsync();

                    if (msg != null)
                    {
                        var order = JsonConvert.DeserializeObject <Order>(msg.AsString);

                        using (IServiceScope scope = _serviceProvider.CreateScope())
                        {
                            // Save the order to the DB
                            var context = scope.ServiceProvider.GetRequiredService <PizzaStoreContext>();
                            order.Status = "Preparing";
                            context.Orders.Attach(order);
                            await context.SaveChangesAsync();

                            await PizzaOrdersQueue.DeleteMessageAsync(msg);

                            _logger.LogInformation($"Preparing order {order.OrderId}");

                            // Send Preparing status
                            var channel = new Channel("localhost:50051", ChannelCredentials.Insecure);
                            var client  = new PizzaOrderStatusClient(channel);
                            var ack     = await client.SendStatusAsync(order.ToStatusUpdate());

                            _logger.LogInformation($"Status update ack: {ack.Message}");

                            await Task.Delay(10000, stoppingToken); // Prepare the pizza

                            // Put the pizza order on the delivery queue
                            await PizzaDeliveryQueue.AddMessageAsync(new CloudQueueMessage(JsonConvert.SerializeObject(order)));

                            _logger.LogInformation($"Order {order.OrderId} sent for delivery");
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"Error preparing pizza order: {ex.Message}");
                }

                // Mandatory Pizza Worker break
                await Task.Delay(1000, stoppingToken);
            }
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Pizza delivery worker running at: {time}", DateTimeOffset.Now);
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    var msg = await PizzaDeliveryQueue.GetMessageAsync();

                    if (msg != null)
                    {
                        var order = JsonConvert.DeserializeObject <Order>(msg.AsString);

                        using (IServiceScope scope = _serviceProvider.CreateScope())
                        {
                            // Save the order to the DB
                            var context = scope.ServiceProvider.GetRequiredService <PizzaStoreContext>();
                            order.Status = "Out for delivery";
                            context.Orders.Attach(order);
                            var result = await context.SaveChangesAsync();

                            await PizzaDeliveryQueue.DeleteMessageAsync(msg);

                            _logger.LogInformation($"Order {order.RequestId} out for delivery");

                            // Send delivery status
                            var                    startPosition    = order.CurrentLocation;
                            var                    dispatchTime     = DateTime.Now;
                            var                    deliveryDuration = TimeSpan.FromSeconds(20);
                            var                    proportionOfDeliveryCompleted = 0d;
                            StatusUpdate           statusUpdate = order.ToStatusUpdate();
                            PizzaOrderStatusClient client       = default;
                            HttpClient             httpClient   = default;
                            Ack                    ack          = default;
                            var                    httpHandler  = new HttpClientHandler();
                            // Return `true` to allow certificates that are untrusted/invalid
                            httpHandler.ServerCertificateCustomValidationCallback =
                                HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
                            httpHandler.UseProxy = false;
                            while (proportionOfDeliveryCompleted == 0d)
                            {
                                if (DateTime.Now > dispatchTime.Add(deliveryDuration))
                                {
                                    proportionOfDeliveryCompleted -= 1;
                                }
                            }
                            {
                                proportionOfDeliveryCompleted = Math.Min(1, (DateTime.Now - dispatchTime).TotalMilliseconds / deliveryDuration.TotalMilliseconds);
                                _logger.LogInformation($"Proportion complete for order {order.RequestId}: {proportionOfDeliveryCompleted}");
                                order.CurrentLocation = LatLong.Interpolate(startPosition, order.DeliveryLocation, proportionOfDeliveryCompleted);

                                var channel = GrpcChannel.ForAddress("https://localhost:54001/",
                                                                     new GrpcChannelOptions {
                                    HttpHandler = httpHandler
                                });
                                client = new PizzaOrderStatusClient(channel);

                                //httpClient = new HttpClient { BaseAddress = new Uri(UriString) };

                                //httpClient.Timeout = new TimeSpan(0, 3, 0);
                                //client = GrpcClient.Create<PizzaOrderStatusClient>(httpClient);
                                ack = await client.SendStatusAsync(statusUpdate);


                                _logger.LogInformation($"Status update ack: {ack.Message}");

                                await Task.Delay(1000, stoppingToken);
                            }

                            order.Status = "Delivered";
                            context.Orders.Attach(order);
                            await context.SaveChangesAsync();

                            _logger.LogInformation($"Order {order.RequestId} delivered");

                            ack = await client.SendStatusAsync(order.ToStatusUpdate());

                            _logger.LogInformation($"Status update ack: {ack.Message}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"Error deliverying pizza order: {ex.Message}");
                }

                // Mandatory Pizza delivery worker break
                await Task.Delay(1000, stoppingToken);
            }
        }
Exemple #3
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Pizza delivery worker running at: {time}", DateTimeOffset.Now);
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    var msg = await PizzaDeliveryQueue.GetMessageAsync();

                    if (msg != null)
                    {
                        var order = JsonConvert.DeserializeObject <Order>(msg.AsString);

                        using (IServiceScope scope = _serviceProvider.CreateScope())
                        {
                            // Save the order to the DB
                            var context = scope.ServiceProvider.GetRequiredService <PizzaStoreContext>();
                            order.Status = "Out for delivery";
                            context.Orders.Attach(order);
                            await context.SaveChangesAsync();

                            await PizzaDeliveryQueue.DeleteMessageAsync(msg);

                            _logger.LogInformation($"Order {order.OrderId} out for delivery");

                            // Send delivery status
                            var startPosition    = order.CurrentLocation;
                            var dispatchTime     = DateTime.Now;
                            var deliveryDuration = TimeSpan.FromSeconds(20);
                            var proportionOfDeliveryCompleted = 0d;
                            var channel = new Channel("localhost:50051", ChannelCredentials.Insecure);
                            var client  = new PizzaOrderStatusClient(channel);
                            Ack ack;

                            while (proportionOfDeliveryCompleted < 1)
                            {
                                proportionOfDeliveryCompleted = Math.Min(1, (DateTime.Now - dispatchTime).TotalMilliseconds / deliveryDuration.TotalMilliseconds);
                                _logger.LogInformation($"Proportion complete for order {order.OrderId}: {proportionOfDeliveryCompleted}");
                                order.CurrentLocation = LatLong.Interpolate(startPosition, order.DeliveryLocation, proportionOfDeliveryCompleted);

                                ack = await client.SendStatusAsync(order.ToStatusUpdate());

                                _logger.LogInformation($"Status update ack: {ack.Message}");

                                await Task.Delay(1000, stoppingToken);
                            }

                            order.Status = "Delivered";
                            context.Orders.Attach(order);
                            await context.SaveChangesAsync();

                            _logger.LogInformation($"Order {order.OrderId} delivered");

                            ack = await client.SendStatusAsync(order.ToStatusUpdate());

                            _logger.LogInformation($"Status update ack: {ack.Message}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"Error deliverying pizza order: {ex.Message}");
                }

                // Mandatory Pizza delivery worker break
                await Task.Delay(1000, stoppingToken);
            }
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Pizza worker running at: {time}", DateTimeOffset.Now);
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    var msg = await PizzaOrdersQueue.GetMessageAsync().ConfigureAwait(false);

                    if (msg != null)
                    {
                        var order = JsonConvert.DeserializeObject <Order>(msg.AsString);

                        using (IServiceScope scope = _serviceProvider.CreateScope())
                        {
                            // Save the order to the DB
                            var context = scope.ServiceProvider.GetRequiredService <PizzaStoreContext>();
                            order.Status = "Preparing";

                            context.Orders.Update(order);
                            await context.SaveChangesAsync().ConfigureAwait(false);

                            await PizzaOrdersQueue.DeleteMessageAsync(msg).ConfigureAwait(false);

                            _logger.LogInformation($"Preparing order {order.RequestId}");

                            // Send Preparing status
                            StatusUpdate           statusUpdate = order.ToStatusUpdate();
                            PizzaOrderStatusClient client       = default;
                            HttpClient             httpClient   = default;
                            Ack ack         = default;
                            var httpHandler = new HttpClientHandler();
                            // Return `true` to allow certificates that are untrusted/invalid
                            httpHandler.ServerCertificateCustomValidationCallback =
                                HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
                            httpHandler.UseProxy = false;

                            var channel = GrpcChannel.ForAddress("https://localhost:54001/",
                                                                 new GrpcChannelOptions {
                                HttpHandler = httpHandler
                            });
                            client = new PizzaOrderStatusClient(channel);

                            //httpClient = new HttpClient { BaseAddress = new Uri(UriString) };

                            //httpClient.Timeout = new TimeSpan(0, 3, 0);
                            //client = GrpcClient.Create<PizzaOrderStatusClient>(httpClient);
                            ack = await client.SendStatusAsync(statusUpdate);



                            _logger.LogInformation($"Status update ack: {ack.Message}");

                            await Task.Delay(10000, stoppingToken); // Prepare the pizza

                            // Put the pizza order on the delivery queue
                            await PizzaDeliveryQueue.AddMessageAsync(new CloudQueueMessage(JsonConvert.SerializeObject(order)));

                            _logger.LogInformation($"Order {order.RequestId} sent for delivery");
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"Error preparing pizza order: {ex.Message}");
                }

                // Mandatory Pizza Worker break
                await Task.Delay(1000, stoppingToken);
            }
        }