AWS SQS:我们如何使用消息

AWS SQS: how do we consume message

我想将我的同步 API 之一转换为异步。我相信队列是做到这一点的一种方式。就像发布者将消息(同步地)推送到队列中,消费者 API 从队列中消费该消息。

我很想知道使用 AWS SimpleQueueService 消息的正确方法是什么。队列可以调用 API 来将消息传递给它,或者唯一的方法是轮询队列。但是我相信轮询会让我们的系统忙于等待,所以最好队列将消息传递给API。

可能的方法是什么?

如果你想从 SQS 消费你有以下方法:

如果您打算检索以获取回复,您还可以利用 virtual queues

在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

编写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();
}

从队列中读取消息

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

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