用ElasticMQ在本地模拟使用AWS的SQS

时间:2024-10-13 07:45:12

如果开发使用SQS的功能,应该会遇到如何进行本地测试的问题。

ElasticMQ 实现了Amazon SQS-compatible interface,可以在本地在模拟AWS的SQS进行测试。

本例子主要通过docker启动,并用aws-cli 进行简易测试。

Dockerfile中的内容,主要指定版本等信息,这个例子中使用的是一个较早的版本0.11.0,目前的最新版是1.1.0

FROM java:8

ADD /softwaremill-public/elasticmq-server-0.11. /elasticmq/elasticmq-server-0.11.
EXPOSE 9324
ENTRYPOINT ["java","-jar","/elasticmq/elasticmq-server-0.11."]

编译image

  1. $ docker build -t rand/elasticmq:0.11.0 .
  2. [+] Building 95.8s (7/7) FINISHED
  3. => [internal] load build definition from Dockerfile 0.1s
  4. => => transferring dockerfile: 270B 0.0s
  5. => [internal] load .dockerignore 0.0s
  6. => => transferring context: 2B 0.0s
  7. => [internal] load metadata for /library/java:8 0.0s
  8. => https://s3-eu-west-1./softwaremill-public/elasticmq-server-0.11.0.jar 0.0s
  9. => [1/2] FROM /library/java:8 0.1s
  10. => => resolve /library/java:8 0.0s
  11. => [2/2] ADD https://s3-eu-west-1./softwaremill-public/elasticmq-server-0.11.0.jar /ela 0.1s
  12. => exporting to image 0.1s
  13. => => exporting layers 0.1s
  14. => => writing image sha256:bc0958931c70dc3c69047c445c84ce83161245b85611b76713e438c3c9634c19 0.0s
  15. => => naming to /rand/elasticmq:0.11.0 0.0s

 启动

  1. docker run -d --name=elasticmq -p 9324:9324 rand/elasticmq:0.11.0
  2. 67c25dd09eb0808dd0518ba4298ff7a38c354e73a9d670bf9d850e5ad12a89fb

 

在本地使用aws命令的前提,需要首先安装好aws-cli,并且设置好configure信息

确认一下是否有Q存在,因为刚刚启动,应该是什么都没有的。

$ aws sqs list-queues --endpoint-url http://localhost:9324

创建一个测试的Q

  1. $ aws sqs create-queue --queue-name test-queue --endpoint-url http://localhost:9324
  2. {
  3.     "QueueUrl": "http://localhost:9324/queue/test-queue"
  4. }

再次确认Q是否创建

  1. $ aws sqs list-queues --endpoint-url http://localhost:9324
  2. {
  3. "QueueUrls": [
  4. "http://localhost:9324/queue/test-queue"
  5. ]
  6. }

向Q中发送消息

  1. $ aws sqs send-message --queue-url http://localhost:9324/queue/test-queue --message-body "Information about the largest city in Any Region." --endpoint-url http://localhost:9324
  2. {
  3. "MD5OfMessageBody": "51b0a3256d59467f973009b739163aa0",
  4. "MD5OfMessageAttributes": "d41d8cd98f00b204e9800998ecf8427e",
  5. "MessageId": "2f2af1fc-dbf7-40a6-8783-756181eeb737"
  6. }

从Q中接受消息

  1. $ aws sqs receive-message --queue-url http://localhost:9324/queue/test-queue --endpoint-url http://localhost:9324
  2. {
  3. "Messages": [
  4. {
  5. "MessageId": "2f2af1fc-dbf7-40a6-8783-756181eeb737",
  6. "ReceiptHandle": "2f2af1fc-dbf7-40a6-8783-756181eeb737#0893169f-63c7-47ef-bde2-5ad26fad7e1d",
  7. "MD5OfBody": "51b0a3256d59467f973009b739163aa0",
  8. "Body": "Information about the largest city in Any Region.",
  9. "MD5OfMessageAttributes": "d41d8cd98f00b204e9800998ecf8427e"
  10. }
  11. ]
  12. }