简体   繁体   English

AWS SQS:我们如何使用消息

[英]AWS SQS: how do we consume message

I want to convert one of my synchronous API into asynchronous.我想将我的同步 API 之一转换为异步。 And I believe queue are one way to do this.我相信队列是做到这一点的一种方法。 Like a publisher will push(synchronously) the message into queue which will be consumed by consumer API from the queue.就像发布者将消息推送(同步)到队列中,消费者 API 从队列中消费该消息。

I was curious to know what is the right way of consuming AWS SimpleQueueService messages.我很想知道使用 AWS SimpleQueueService 消息的正确方法是什么。 Can queue call an API to deliver the message to it or the only way to do is to poll the queue.可以队列调用 API 将消息传递给它,或者唯一的方法是轮询队列。 But I believe that polling will make our system busy waiting so it is best the queue deliver the message to API.但我相信轮询会让我们的系统忙于等待,所以最好是队列将消息传递到 API。

What is possible way to do this?有什么可能的方法来做到这一点?

If you want to consume from SQS you have the following methods:如果你想从 SQS 消费,你有以下方法:

If you intend to retrieve to get responses back you can also take advantage of virtual queues .如果您打算检索以获取响应,您还可以利用虚拟队列

In application.yml在 application.yml

sqs:
region: ap-south-1
accessKeyId: arunsinghgujjar
secretAccessKey: jainpurwalearunsingh/saharanpursepauchepuna
cloud:
aws:
end-point:
uri: https://arun-learningsubway-1.amazonaws.com/9876974864/learningsubway_SQS.fifo
queue:
max-poll-time: 20
max-messages: 10
fetch-wait-on-error: 60
enabled: true
content: sqs

Write SQS client编写 SQS 客户端

public String sendMessage(MessageDistributionEvent messageDistributionEvent) {
SendMessageResponse sendMessage = null;
try {
Map<String, MessageAttributeValue> attributes = new HashMap<>();

String recepList = "";
for (Integer myInt : messageDistributionEvent.getRecipients()) {
recepList = recepList + "_" + myInt;
}
SendMessageRequest sendMsgRequest = SendMessageRequest.builder()
.queueUrl(url)
.messageBody(messageDistributionEvent.getChannelId() + "_" + messageDistributionEvent.getMessageId() + "" + recepList)
.messageGroupId("1")
.messageAttributes(attributes)
.build();
sendMessage = sqsClient.sendMessage(sendMsgRequest);
} catch (Exception ex) {
log.info("failed to send message :" + ex);
}
return sendMessage.sequenceNumber();
}

Read Message from Queue从队列中读取消息

ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder()
.queueUrl(url)
.waitTimeSeconds(maxPollTime)
.maxNumberOfMessages(maxMessages)
.messageAttributeNames("MessageLabel")
.build();
List<Message> sqsMessages = sqsClient.receiveMessage(receiveMessageRequest).messages();

Reference https://learningsubway.com/read-write-data-into-aws-sqs-using-java/参考https://learningsubway.com/read-write-data-into-aws-sqs-using-java/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM