示例#1
0
        public async Task SendMessage_HasMessageTypeAttributeAndBody()
        {
            //Arrange
            var queueName    = Guid.NewGuid().ToString();
            var firstMessage = new FirstMessage {
                Value = "value1"
            };
            var secondMessage = new SecondMessage {
                Value = "value2"
            };
            var thirdMessage = new ThirdMessage {
                Value = "value3"
            };

            var sqsClient = new AmazonSQSClient(
                AppConfig.AccessKey,
                AppConfig.SecretKey,
                new AmazonSQSConfig {
                ServiceURL = AppConfig.ServiceUrl
            });

            await sqsClient.CreateQueueAsync(queueName);

            var queueUrl = (await sqsClient.GetQueueUrlAsync(queueName)).QueueUrl;

            //Act
            await sqsClient.SendMessageAsync(queueUrl, firstMessage);

            await sqsClient.SendMessageAsync(queueUrl, secondMessage);

            await sqsClient.SendMessageAsync(queueUrl, thirdMessage, typeof(ThirdMessage));

            var response = await sqsClient.ReceiveMessageAsync(new ReceiveMessageRequest
            {
                QueueUrl              = queueUrl,
                MaxNumberOfMessages   = 3,
                MessageAttributeNames = new List <string> {
                    "All"
                }
            });

            var messageTypes = response.Messages
                               .Select(message => JsonConvert.DeserializeObject <MessageBody>(message.Body))
                               .Select(body => body.MessageAttributes.Single(pair => pair.Key == "MessageType").Value.Value)
                               .ToList();

            var messages = response.Messages
                           .Select(message => JsonConvert.DeserializeObject <MessageBody>(message.Body))
                           .Select(body => body.Message)
                           .ToArray();

            //Assert
            new[] { nameof(FirstMessage), nameof(SecondMessage), nameof(ThirdMessage) }
            .ShouldAllBe(s => messageTypes.Contains(s));

            new [] { firstMessage.Value, secondMessage.Value, thirdMessage.Value }
            .ShouldAllBe(s => messages.Any(m => m.Contains(s)));
        }
        public override async Task PostDocumentAsync <T>(PostDocument <T> doc, CancellationToken ct = default)
        {
            var request = new SendMessageRequest();

            request.QueueUrl               = PostDocumentQueueUrl;
            request.MessageBody            = JsonSerializer.Serialize(doc);
            request.MessageGroupId         = CreateDocName(doc.Type, doc.Name);
            request.MessageDeduplicationId = Guid.NewGuid().ToString();
            await _sqs.SendMessageAsync(request, ct);
        }
示例#3
0
        public async Task <IActionResult> PutTitle([FromBody] Title newTitle)
        {
            await PutTitleToDynamo(newTitle);

            await SqsClient.SendMessageAsync(TitlesQueue, JsonConvert.SerializeObject(new
            {
                EventType = "PUT",
                Payload   = newTitle,
            }, JsonSerializerSettings));

            return(Ok());
        }
示例#4
0
        public override async Task SendAsync(string correlationId, MessageEnvelope message)
        {
            CheckOpened(correlationId);

            // Set the message sent time
            message.SentTime = DateTime.UtcNow;

            await _client.SendMessageAsync(CreateSendMessageRequest(message, _contentBasedDupication, _queue), _cancel.Token);

            _counters.IncrementOne("queue." + Name + ".sent_messages");
            _logger.Debug(message.CorrelationId, "Sent message {0} via {1}", message, this);

            await Task.Delay(0);
        }
示例#5
0
        /// <summary>
        ///
        /// <para>CustomPublish:</para>
        ///
        /// <para>Publishes the given message to given custom topic</para>
        ///
        /// <para>Check <seealso cref="IBPubSubServiceInterface.CustomPublish"/> for detailed documentation</para>
        ///
        /// </summary>
        public bool CustomPublish(string _CustomTopic, string _CustomMessage, Action <string> _ErrorMessageAction = null)
        {
            if (_CustomTopic != null && _CustomTopic.Length > 0 &&
                _CustomMessage != null && _CustomMessage.Length > 0 &&
                BUtility.CalculateStringMD5(_CustomTopic, out string TopicMD5, _ErrorMessageAction))
            {
                if (EnsureQueueExists(TopicMD5, out string QueueUrl, _ErrorMessageAction))
                {
                    string TimestampHash = null;
                    UniqueMessageDeliveryEnsurer?.Publish_PrependTimestampToMessage(ref _CustomMessage, out TimestampHash);

                    try
                    {
                        if (UniqueMessageDeliveryEnsurer != null)
                        {
                            if (UniqueMessageDeliveryEnsurer.Publish_EnsureUniqueDelivery(_CustomTopic, TimestampHash, _ErrorMessageAction))
                            {
                                using (var SendMessageTask = SQSClient.SendMessageAsync(QueueUrl, _CustomMessage))
                                {
                                    SendMessageTask.Wait();
                                }
                            }
                            else
                            {
                                _ErrorMessageAction?.Invoke("BPubSubServiceAWS->CustomPublish: UniqueMessageDeliveryEnsurer has failed.");
                                return(false);
                            }
                        }
                        else
                        {
                            using (var SendMessageTask = SQSClient.SendMessageAsync(QueueUrl, _CustomMessage))
                            {
                                SendMessageTask.Wait();
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        _ErrorMessageAction?.Invoke("BPubSubServiceAWS->CustomPublish: " + e.Message + ", Trace: " + e.StackTrace);
                        if (e.InnerException != null && e.InnerException != e)
                        {
                            _ErrorMessageAction?.Invoke("BPubSubServiceAWS->CustomPublish->Inner: " + e.InnerException.Message + ", Trace: " + e.InnerException.StackTrace);
                        }
                        return(false);
                    }
                    return(true);
                }
            }
            return(false);
        }
示例#6
0
        public async Task CreateMessageAsync(ReducedBandKey key)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }
            SendMessageRequest  message  = new SendMessageRequest(this.pairQueueUrl, JsonConvert.SerializeObject(key));
            SendMessageResponse response = await client.SendMessageAsync(message);

            if (response.HttpStatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception($"failed to populate SQS: {this.pairQueueUrl} with code: {response.HttpStatusCode}");
            }
            return;
        }
        /// <summary>
        /// Initialize the Amazon SQS client object and use the
        /// SendMessageAsync method to send a message to an Amazon SQS queue.
        /// </summary>
        public static async Task Main()
        {
            string messageBody = "This is a sample message to send to the example queue.";
            string queueUrl    = "https://sqs.us-east-2.amazonaws.com/0123456789ab/Example_Queue";

            // Create an Amazon SQS client object using the
            // default user. If the AWS Region you want to use
            // is different, supply the AWS Region as a parameter.
            IAmazonSQS client = new AmazonSQSClient();

            var request = new SendMessageRequest
            {
                MessageBody = messageBody,
                QueueUrl    = queueUrl,
            };

            var response = await client.SendMessageAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"Successfully sent message. Message ID: {response.MessageId}");
            }
            else
            {
                Console.WriteLine("Could not send message.");
            }
        }
示例#8
0
        public void SendToSns(string jsonPayload)
        {
            var tries = 10;

            while (true)
            {
                try
                {
                    var request = new SendMessageRequest()
                    {
                        QueueUrl = "https://sqs.us-east-1.amazonaws.com/105029661252/start-checkout", // Leandro
                        //QueueUrl = "https://sqs.us-east-1.amazonaws.com/106868270748/start-checkout", // Carlos
                        MessageBody = jsonPayload
                    };

                    _sqsClient.SendMessageAsync(request).Wait();
                    break;
                }
                catch
                {
                    if (--tries == 0)
                    {
                        throw;
                    }
                    Thread.Sleep(1500);
                }
            }
        }
示例#9
0
        static async Task Main()
        {
            var          client   = new AmazonSQSClient();
            const string queueUrl = "<please input your queue's url>";

            // メッセージをエンキューする
            await client.SendMessageAsync(queueUrl, "Hello SQS !!");

            // 複数のメッセージをエンキューする
            await client.SendMessageBatchAsync(queueUrl, Enumerable.Range(0, 5).Select(i => new SendMessageBatchRequestEntry
            {
                Id = i.ToString(),
                MessageBody = "Hello SQS !! - " + i,
            }).ToList());

            // メッセージをデキューする
            var receiveMessageRequest = new ReceiveMessageRequest
            {
                QueueUrl            = queueUrl,
                MaxNumberOfMessages = 10,
            };
            var messages = (await client.ReceiveMessageAsync(receiveMessageRequest)).Messages;

            foreach (var message in messages)
            {
                // メッセージの内容を表示する
                Console.WriteLine(message.Body);

                // メッセージを削除する
                await client.DeleteMessageAsync(queueUrl, message.ReceiptHandle);
            }
        }
示例#10
0
        /// <summary>
        /// Requeues the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="delayMilliseconds">Number of milliseconds to delay delivery of the message.</param>
        public void Requeue(Message message, int delayMilliseconds)
        {
            try
            {
                Reject(message, false);

                using (var client = new AmazonSQSClient(_credentials))
                {
                    _logger.Value.InfoFormat("SqsMessageConsumer: requeueing the message {0}", message.Id);

                    message.Header.Bag.Remove("ReceiptHandle");
                    var request = new SendMessageRequest(_queueUrl, JsonConvert.SerializeObject(message))
                    {
                        DelaySeconds = (int)TimeSpan.FromMilliseconds(delayMilliseconds).TotalSeconds
                    };

                    client.SendMessageAsync(request).Wait();
                }

                _logger.Value.InfoFormat("SqsMessageConsumer: requeued the message {0}", message.Id);
            }
            catch (Exception exception)
            {
                _logger.Value.ErrorException("SqsMessageConsumer: Error purging queue {0}", exception, _queueUrl);
                throw;
            }
        }
示例#11
0
        public async Task <Entities.Cart> CartCheckout(string cartId, CartCheckoutRequest payload, string controlId)
        {
            var databaseCart = await GetCartById(cartId);

            if (databaseCart == null)
            {
                throw new CartNotFoundException($"Cart {cartId} not found");
            }

            if (databaseCart.Status != STATUS_PENDING)
            {
                throw new InvalidCartException($"Cart {databaseCart.Id} has status {databaseCart.Status}");
            }

            databaseCart.ControlId    = controlId;
            databaseCart.CurrencyCode = payload.CurrencyCode;

            var cartQueueMessage = _mapper.Map <StartCheckoutQueueMessage>(databaseCart);

            await _amazonSQSClient.SendMessageAsync(new SendMessageRequest()
            {
                QueueUrl    = _configuration["AmazonSQSCheckoutQueueURL"],
                MessageBody = JsonConvert.SerializeObject(cartQueueMessage)
            });

            databaseCart.Status = STATUS_DONE;

            await _cartsCollection.ReplaceOneAsync(cart => cart.Id == cartId, databaseCart);

            return(databaseCart);
        }
        /// <summary>
        /// Invoke the command and get the response from SQS
        /// </summary>
        /// <param name="request"> The request to perform </param>
        /// <returns> The response </returns>
        public Response Invoke(Request request)
        {
            var response     = new Response();
            var queueRequest = request as QueueRequest;

            queueRequest.Validate();

            var sqsClient = new AmazonSQSClient();

            var sqsResponse = sqsClient.SendMessageAsync(
                QueueHelper.RequestQueueUrl,
                JsonConvert.SerializeObject(queueRequest)
                ).Result;

            var qp = new QueueProcess()
            {
                QueueId = sqsResponse.MessageId
            };

            this.connection.Insert <QueueProcess>(qp);

            response.Payload = sqsResponse.MessageId;
            response.Status  = HttpCode.Accepted;

            return(response);
        }
示例#13
0
        bool IQueueClientService.SendMessage(AppointmentModel appointment, string operation)
        {
            IAmazonSQS sqs      = new AmazonSQSClient(RegionEndpoint.USEast2);
            var        queueUrl = sqs.GetQueueUrlAsync(Configuration.GetValue <string>("DASAppointmentsQueueName")).Result.QueueUrl;
            var        message  = new SQSMessageModel
            {
                Op          = operation,
                Appointment = appointment
            };
            var sqsMessageRequest = new SendMessageRequest
            {
                QueueUrl       = queueUrl,
                MessageBody    = JsonConvert.SerializeObject(message),
                MessageGroupId = "Appointments",
                //MessageDeduplicationId = Guid.NewGuid().ToString(),
            };

            try
            {
                SendMessageResponse response = sqs.SendMessageAsync(sqsMessageRequest).Result;
            }
            catch (Exception ex)
            {
                throw ex;
            }



            return(true);
        }
示例#14
0
        public async Task <string> SendMessage(Orden orden)
        {
            string strBody = JsonConvert.SerializeObject(orden);

            var client = new AmazonSQSClient();

            var sendMessageRequest = new SendMessageRequest
            {
                MessageAttributes = new Dictionary <string, MessageAttributeValue>
                {
                    {
                        "orderid", new MessageAttributeValue
                        {
                            DataType = "String", StringValue = orden.Id.ToString()
                        }
                    }
                },
                MessageBody            = strBody,
                QueueUrl               = "https://sqs.us-east-2.amazonaws.com/528726598722/pica-ordenes-queue.fifo",
                MessageDeduplicationId = orden.Id.ToString(),
                MessageGroupId         = "ordenes-queue"
            };

            var sendMessageResponse = await client.SendMessageAsync(sendMessageRequest);

            return(sendMessageResponse.MessageId);
        }
示例#15
0
        public static void Main(string[] args)
        {
            var credentials = new StoredProfileAWSCredentials("default");
            var sqsClient   = new AmazonSQSClient(credentials, RegionEndpoint.EUWest1);

            // Create queue

            var createQueueRequest = new CreateQueueRequest
            {
                QueueName = "BFQueue"
            };

            CreateQueueResponse queue = sqsClient.CreateQueueAsync(createQueueRequest).Result;

            Console.WriteLine("Send a message");

            string message = null;

            while ((message = Console.ReadLine()) != "q")
            {
                var sendMessageRequest = new SendMessageRequest(queue.QueueUrl, message)
                {
                };

                sqsClient.SendMessageAsync(sendMessageRequest);
            }
        }
示例#16
0
        private async Task <string> QueueMessage(ILambdaContext context, string url)
        {
            try
            {
                string myQueueURL = "https://sqs.ap-southeast-2.amazonaws.com/632298589294/mjsdemo-sqs";

                var request = new SendMessageRequest
                {
                    DelaySeconds = (int)TimeSpan.FromSeconds(5).TotalSeconds,
                    MessageBody  = url,
                    QueueUrl     = myQueueURL
                };

                context.Logger.LogLine("Send message\n");
                var response = await client.SendMessageAsync(request);

                context.Logger.LogLine("Message sent\n");
                return(response.MessageId);
            }
            catch (Exception ex)
            {
                context.Logger.LogLine($"Error: {ex.Message}");
                throw;
            }
        }
示例#17
0
        public async Task <HttpStatusCode> PushMessageToQueueAsync(T model, string awsAccessKeyId, string awsSecretAccessKey)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (String.IsNullOrEmpty(awsAccessKeyId))
            {
                throw new ArgumentNullException(nameof(awsAccessKeyId));
            }
            if (String.IsNullOrEmpty(awsSecretAccessKey))
            {
                throw new ArgumentNullException(nameof(awsSecretAccessKey));
            }
            try
            {
                IAmazonSQS sqs         = new AmazonSQSClient(awsAccessKeyId, awsSecretAccessKey, RegionEndpoint.APSouth1);
                String     emailString = JsonConvert.SerializeObject(model);

                SendMessageRequest sendMessageRequest = new SendMessageRequest
                {
                    MessageBody = emailString,
                    QueueUrl    = QueueUrl
                };
                SendMessageResponse response = await sqs.SendMessageAsync(sendMessageRequest);

                return(response.HttpStatusCode);
            }
            catch (Exception ex)
            {
                throw new Exception("Error Pushing to SQS", ex);
            }
        }
示例#18
0
        public async Task SendMssageExample()
        {
            // Create service client using the SDK's default logic for determining AWS credentials and region to use.
            // For information configuring service clients checkout the .NET developer guide: https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config.html
            AmazonSQSClient client = new AmazonSQSClient();

            var sendMessageRequest = new SendMessageRequest
            {
                DelaySeconds      = 10,
                MessageAttributes = new Dictionary <string, MessageAttributeValue>
                {
                    { "Title", new MessageAttributeValue {
                          DataType = "String", StringValue = "The Whistler"
                      } },
                    { "Author", new MessageAttributeValue {
                          DataType = "String", StringValue = "John Grisham"
                      } },
                    { "WeeksOn", new MessageAttributeValue {
                          DataType = "Number", StringValue = "6"
                      } }
                },
                MessageBody = "Information about current NY Times fiction bestseller for week of 12/11/2016.",
                QueueUrl    = "SQS_QUEUE_URL"
            };

            var response = await client.SendMessageAsync(sendMessageRequest);

            Console.WriteLine("Sent a message with id : {0}", response.MessageId);
        }
示例#19
0
        static void SendMessage(AmazonSQSClient client)
        {
            string      id = Guid.NewGuid().ToString();
            DOEvent     ev = new DOEvent();
            DOParameter pa = new DOParameter();

            ev.event_id   = id;
            ev.event_name = "purchase";
            ev.user_id    = id;
            pa.order_id   = id;
            pa.currency   = "krw";
            pa.price      = 300;
            ev.parameters = pa;

            var req = new SendMessageRequest();

            req.QueueUrl    = QUEUE_URL;
            req.MessageBody = JsonConvert.SerializeObject(ev);
            var response = client.SendMessageAsync(req).Result;

            Console.WriteLine("status code: " + response.HttpStatusCode);
            Console.WriteLine("md5 body: " + response.MD5OfMessageBody);
            Console.WriteLine("msg id: " + response.MessageId);
            Console.WriteLine("msg length: " + response.ContentLength);
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Initializing Amazon SQS Client and getting queue URL...");
            var sqsClient          = new AmazonSQSClient();
            var getQueueUrlRequest = new GetQueueUrlRequest
            {
                QueueName = "DemoMasterWorkerPattern",
                QueueOwnerAWSAccountId = "545983628851"
            };
            var getQueueUrlResponse = sqsClient.GetQueueUrlAsync(getQueueUrlRequest).Result;
            var queueUrl            = getQueueUrlResponse.QueueUrl;

            Console.WriteLine($"Received Queue URL: {queueUrl}");

            while (true)
            {
                Console.Write("Type a message to be sent to the queue or type 'exit' to quit: ");
                var message = Console.ReadLine();
                if (string.Equals(message, "exit", StringComparison.OrdinalIgnoreCase))
                {
                    break;
                }

                Console.WriteLine($"Sending message with content '{message}' to the queue...");
                var sendMessageRequest = new SendMessageRequest();
                sendMessageRequest.QueueUrl    = queueUrl;
                sendMessageRequest.MessageBody = message;
                var sendMessageResponse = sqsClient.SendMessageAsync(sendMessageRequest).Result;
                Console.WriteLine("Message has been sent.");
                Console.WriteLine($"HttpStatusCode: {sendMessageResponse.HttpStatusCode}");
            }
        }
示例#21
0
            public static void SendMessage(string messageBody, string queueUrl,
                                           string messageGroupId = null, string messageDeduplicationId = null)
            {
                var request = new SendMessageRequest
                {
                    MessageBody = messageBody,
                    QueueUrl    = queueUrl
                };

                //Used to group messages in a fifo queue
                if (!string.IsNullOrWhiteSpace(messageGroupId))
                {
                    request.MessageGroupId = messageGroupId;
                }

                //Used to desambiguate messages in a fifo queue
                if (!string.IsNullOrWhiteSpace(messageDeduplicationId))
                {
                    request.MessageDeduplicationId = messageDeduplicationId;
                }

                var task = client.SendMessageAsync(request);

                task.Wait();
            }
示例#22
0
        public void SendMessage()
        {
            IAmazonSQS sqs = new AmazonSQSClient(RegionEndpoint.USEast1);

            var sqsRequest = new CreateQueueRequest
            {
                QueueName = "CartQueue"
            };

            var createQueueResponse = sqs.CreateQueueAsync(sqsRequest).Result;

            var queueUrl = createQueueResponse.QueueUrl;

            var listQueueRequest = new ListQueuesRequest();

            var listQueueResponse = sqs.ListQueuesAsync(listQueueRequest);

            Console.WriteLine($"List of amazon queue url. \n");

            foreach (var item in listQueueResponse.Result.QueueUrls)
            {
                Console.WriteLine($"Queue URL{item}");
            }

            Console.WriteLine($"Sending Message. \n");

            var sqsMessageRequest = new SendMessageRequest
            {
                QueueUrl    = queueUrl,
                MessageBody = "Message Bodykkkkk"
            };

            sqs.SendMessageAsync(sqsMessageRequest);
        }
示例#23
0
        public async Task PublishMovie(MovieModel movieData)
        {
            try
            {
                var data = JsonConvert.SerializeObject(movieData);

                var sendMessageRequest = new SendMessageRequest(_queueUrl, data);

                sendMessageRequest.MessageAttributes.Add("Publisher",
                                                         new MessageAttributeValue()
                {
                    DataType    = "String",
                    StringValue = "AwsSQSLabs.Web"
                }
                                                         );

                var sendMessageResponse = await _sqsClient.SendMessageAsync(sendMessageRequest);

                // save queue data
                _logger.LogInformation($"MessageId: {sendMessageResponse.MessageId}, SequenceNumber: {sendMessageResponse.SequenceNumber}");
                var metadata = sendMessageResponse.ResponseMetadata;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Couldn't publish an movie to SQS");
                throw;
            }
        }
        static async Task PushToSQS(IClient client, string accountId)
        {
            var source     = new CancellationTokenSource();
            var sqsClient  = new AmazonSQSClient(RegionEndpoint.USEast1);
            var urlRequest = new GetQueueUrlRequest
            {
                QueueName = AWSConstructs.Names.FroniusIngressQueue,
                QueueOwnerAWSAccountId = accountId
            };
            var url = (await sqsClient.GetQueueUrlAsync(urlRequest))?.QueueUrl;

            if (url == null)
            {
                throw new Exception($"Failed to get SQS URL for: {JsonSerializer.Serialize(urlRequest)}");
            }
            Response?dataLast = null;

            while (true)
            {
                var data = await client.GetPowerFlowRealtimeData(source.Token);

                if (data?.Head.Timestamp == dataLast?.Head.Timestamp)
                {
                    await Task.Delay(10);

                    continue;
                }
                var dataJson = JsonSerializer.Serialize(data);
                var message  = new SendMessageRequest(url, dataJson);
                var response = await sqsClient.SendMessageAsync(message);

                Console.WriteLine($"{response.HttpStatusCode} | {response.MessageId} | {dataJson}");
                dataLast = data;
            }
        }
示例#25
0
        static async Task Main(string[] args)
        {
            string       queueUrl  = $"https://sqs.<Region e.g. us-east-2>.amazonaws.com/<Account number>/{args[0]}";
            const string accessKey = "<Access Key>";
            const string secretKey = "<Secret Key>";

            IAmazonSQS sqsClient = new AmazonSQSClient(accessKey, secretKey, RegionEndpoint.USEast2);

            int i = 1;

            while (true)
            {
                var message = $"{args[1]}-{i++}";
                var request = new SendMessageRequest
                {
                    QueueUrl    = queueUrl,
                    MessageBody = message
                };
                var response = await sqsClient.SendMessageAsync(request);

                Console.Clear();
                if (response != null)
                {
                    Console.WriteLine($"Sent: {message}");
                }
                else
                {
                    Console.WriteLine("Bad Request");
                    break;
                }
                Thread.Sleep(1000);
            }
        }
        public async Task <string> CreateMessage([FromBody] string message)
        {
            var queueUrl = await QueueUrl.Build(_client, QueueName, _sqsConfigParam.QueueAttributes);

            var request = new SendMessageRequest
            {
                QueueUrl    = queueUrl.Value,
                MessageBody = message
            };

            var response = await _client.SendMessageAsync(request);

            if (response.HttpStatusCode == HttpStatusCode.OK)
            {
                var result = new
                {
                    StatusCode = "正常終了",
                    Message    = "SQSへメッセージの登録に成功しました。"
                };
                return(JsonConvert.SerializeObject(result));
            }
            else
            {
                var result = new
                {
                    StatusCode = "エラー",
                    Message    = "SQSへメッセージの登録に失敗しました。"
                };
                return(JsonConvert.SerializeObject(result));
            }
        }
        private static async Task SendMessagesWithInjectedHeadersAsync(AmazonSQSClient sqsClient)
        {
            // Send one message, receive it, and parse it for its headers
            await sqsClient.SendMessageAsync(_singleQueueUrl, "SendMessageAsync_SendMessageRequest");

            var receiveMessageRequest = new ReceiveMessageRequest()
            {
                QueueUrl = _singleQueueUrl,
                MessageAttributeNames = new List <string>()
                {
                    ".*"
                }
            };
            var receiveMessageResponse1 = await sqsClient.ReceiveMessageAsync(receiveMessageRequest);

            await sqsClient.DeleteMessageAsync(_singleQueueUrl, receiveMessageResponse1.Messages.First().ReceiptHandle);

            Common.AssertDistributedTracingHeaders(receiveMessageResponse1.Messages);

            // Send a batch of messages, receive them, and parse them for headers
            var sendMessageBatchRequest = new SendMessageBatchRequest
            {
                Entries = new List <SendMessageBatchRequestEntry>
                {
                    new("message1", "SendMessageBatchAsync: FirstMessageContent"),
                    new("message2", "SendMessageBatchAsync: SecondMessageContent"),
                    new("message3", "SendMessageBatchAsync: ThirdMessageContent")
                },
示例#28
0
        public async void PublishEvent(Event eventData)
        {
            try
            {
                SendMessageRequest sendMessageRequest = new SendMessageRequest(
                    _queueUrl,
                    JsonConvert.SerializeObject(eventData)
                    );

                sendMessageRequest.MessageAttributes.Add(
                    "Publisher",
                    new MessageAttributeValue()
                {
                    DataType    = "String",
                    StringValue = "AwsAspNetCoreLabs. Web"
                }
                    );

                SendMessageResponse sendMessageResponse = await _sqsClient.SendMessageAsync(sendMessageRequest);
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, "Couldn't publish an event to SQS");
                throw;
            }
        }
示例#29
0
        private async Task sendMessage(T messageObject)
        {
            InitializeQueue();

            var queueName = _awsSettings.PubSub.QueueMappings[messageObject.GetType().FullName];
            var queueUrl  = $"{_awsSettings.PubSub.QueueBasePath}/{_awsSettings.PubSub.QueueIdentifier}/{queueName}";

            var message = JsonConvert.SerializeObject(messageObject);

            var sendRequest = new SendMessageRequest()
            {
                QueueUrl    = queueUrl,
                MessageBody = message
            };

            sendRequest.MessageAttributes = new System.Collections.Generic.Dictionary <string, MessageAttributeValue>
            {
                ["Message.Type.FullName"] = new MessageAttributeValue()
                {
                    StringValue = messageObject.GetType().FullName,
                    DataType    = "String",
                }
            };

            var messageResponse = await _client.SendMessageAsync(sendRequest);

            _appLogger.LogMessage($"Message Type: {messageObject.GetType().FullName} queued with MessageId: {messageResponse.MessageId} and HttpStatusCode: {messageResponse.HttpStatusCode}");
        }
示例#30
0
        public void SendMessage()
        {
            while (true)
            {
                var messageData = new SampleData
                {
                    MessageId   = Guid.NewGuid(),
                    MessageBody = DateTime.Now.Millisecond.ToString()
                };

                var messageString = JsonConvert.SerializeObject(messageData);

                var sendRequest = new SendMessageRequest
                {
                    QueueUrl               = _queueUrl,
                    MessageBody            = messageString,
                    MessageGroupId         = MessageGroupId,
                    MessageDeduplicationId = Guid.NewGuid().ToString()
                };
                var result = _client.SendMessageAsync(sendRequest).Result;

                if (result.HttpStatusCode != HttpStatusCode.OK)
                {
                    _logger.Error("Error in sending SQS Request");
                }
                else
                {
                    Stats.Stats.ProducerCounter++;
                }
            }
        }