Amazon sqs是亚马逊提供的线上消息队列服务, 可以实现应用程序解耦,以及可靠性保证。 sqs提供了两种消息队列, 一种是标准消息队列, 一种是先进先出队列(FIFO), 其区别是FIFO是严格有序的,即消息接收的顺序是按照消息发送的顺序来的, 而标准队列是尽最大可能有序, 即不保证一定为有序, 此外FIFO还保证了消息在一定时间内不能重复发出,即使是重复发了, 它也不会把消息发送到队列上。

队列操作

创建队列
AmazonSQS sqs = AmazonSQSClientBuilder.defaultClient();
CreateQueueRequest create_request = new CreateQueueRequest(QUEUE_NAME)
.addAttributesEntry("DelaySeconds", "60")
.addAttributesEntry("MessageRetentionPeriod", "86400"); try {
sqs.createQueue(create_request);
} catch (AmazonSQSException e) {
if (!e.getErrorCode().equals("QueueAlreadyExists")) {
throw e;
}
}
列出队列
AmazonSQS sqs = AmazonSQSClientBuilder.defaultClient();
ListQueuesResult lq_result = sqs.listQueues();
System.out.println("Your SQS Queue URLs:");
for (String url : lq_result.getQueueUrls()) {
System.out.println(url);
}
获取队列Url
AmazonSQS sqs = AmazonSQSClientBuilder.defaultClient();
String queue_url = sqs.getQueueUrl(QUEUE_NAME).getQueueUrl();
删除队列
AmazonSQS sqs = AmazonSQSClientBuilder.defaultClient();
sqs.deleteQueue(queue_url);

消息操作

发送消息
SendMessageRequest send_msg_request = new SendMessageRequest()
.withQueueUrl(queueUrl)
.withMessageBody("hello world")
.withDelaySeconds(5);
sqs.sendMessage(send_msg_request);
批量发送消息
SendMessageBatchRequest send_batch_request = new SendMessageBatchRequest()
.withQueueUrl(queueUrl)
.withEntries(
new SendMessageBatchRequestEntry(
"msg_1", "Hello from message 1"),
new SendMessageBatchRequestEntry(
"msg_2", "Hello from message 2")
.withDelaySeconds(10));
sqs.sendMessageBatch(send_batch_request);
获取消息
List<Message> messages = sqs.receiveMessage(queueUrl).getMessages();
删除消息
for (Message m : messages) {
sqs.deleteMessage(queueUrl, m.getReceiptHandle());
}

使用JMS方法

发送消息
public class TextMessageSender {
public static void main(String args[]) throws JMSException {
ExampleConfiguration config = ExampleConfiguration.parseConfig("TextMessageSender", args); ExampleCommon.setupLogging(); // Create the connection factory based on the config
SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
new ProviderConfiguration(),
AmazonSQSClientBuilder.standard()
.withRegion(config.getRegion().getName())
.withCredentials(config.getCredentialsProvider())
); // Create the connection
SQSConnection connection = connectionFactory.createConnection(); // Create the queue if needed
ExampleCommon.ensureQueueExists(connection, config.getQueueName()); // Create the session
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer( session.createQueue( config.getQueueName() ) ); sendMessages(session, producer); // Close the connection. This closes the session automatically
connection.close();
System.out.println( "Connection closed" );
} private static void sendMessages( Session session, MessageProducer producer ) {
BufferedReader inputReader = new BufferedReader(
new InputStreamReader( System.in, Charset.defaultCharset() ) ); try {
String input;
while( true ) {
System.out.print( "Enter message to send (leave empty to exit): " );
input = inputReader.readLine();
if( input == null || input.equals("" ) ) break; TextMessage message = session.createTextMessage(input);
producer.send(message);
System.out.println( "Send message " + message.getJMSMessageID() );
}
} catch (EOFException e) {
// Just return on EOF
} catch (IOException e) {
System.err.println( "Failed reading input: " + e.getMessage() );
} catch (JMSException e) {
System.err.println( "Failed sending message: " + e.getMessage() );
e.printStackTrace();
}
}
}
同步接收消息
public class SyncMessageReceiver {
public static void main(String args[]) throws JMSException {
ExampleConfiguration config = ExampleConfiguration.parseConfig("SyncMessageReceiver", args); ExampleCommon.setupLogging(); // Create the connection factory based on the config
SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
new ProviderConfiguration(),
AmazonSQSClientBuilder.standard()
.withRegion(config.getRegion().getName())
.withCredentials(config.getCredentialsProvider())
); // Create the connection
SQSConnection connection = connectionFactory.createConnection(); // Create the queue if needed
ExampleCommon.ensureQueueExists(connection, config.getQueueName()); // Create the session
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer( session.createQueue( config.getQueueName() ) ); connection.start(); receiveMessages(session, consumer); // Close the connection. This closes the session automatically
connection.close();
System.out.println( "Connection closed" );
} private static void receiveMessages( Session session, MessageConsumer consumer ) {
try {
while( true ) {
System.out.println( "Waiting for messages");
// Wait 1 minute for a message
Message message = consumer.receive(TimeUnit.MINUTES.toMillis(1));
if( message == null ) {
System.out.println( "Shutting down after 1 minute of silence" );
break;
}
ExampleCommon.handleMessage(message);
message.acknowledge();
System.out.println( "Acknowledged message " + message.getJMSMessageID() );
}
} catch (JMSException e) {
System.err.println( "Error receiving from SQS: " + e.getMessage() );
e.printStackTrace();
}
}
}
异步接收消息
public class AsyncMessageReceiver {
public static void main(String args[]) throws JMSException, InterruptedException {
ExampleConfiguration config = ExampleConfiguration.parseConfig("AsyncMessageReceiver", args); ExampleCommon.setupLogging(); // Create the connection factory based on the config
SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
new ProviderConfiguration(),
AmazonSQSClientBuilder.standard()
.withRegion(config.getRegion().getName())
.withCredentials(config.getCredentialsProvider())
); // Create the connection
SQSConnection connection = connectionFactory.createConnection(); // Create the queue if needed
ExampleCommon.ensureQueueExists(connection, config.getQueueName()); // Create the session
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer( session.createQueue( config.getQueueName() ) ); ReceiverCallback callback = new ReceiverCallback();
consumer.setMessageListener( callback ); // No messages are processed until this is called
connection.start(); callback.waitForOneMinuteOfSilence();
System.out.println( "Returning after one minute of silence" ); // Close the connection. This closes the session automatically
connection.close();
System.out.println( "Connection closed" );
} private static class ReceiverCallback implements MessageListener {
// Used to listen for message silence
private volatile long timeOfLastMessage = System.nanoTime(); public void waitForOneMinuteOfSilence() throws InterruptedException {
for(;;) {
long timeSinceLastMessage = System.nanoTime() - timeOfLastMessage;
long remainingTillOneMinuteOfSilence =
TimeUnit.MINUTES.toNanos(1) - timeSinceLastMessage;
if( remainingTillOneMinuteOfSilence < 0 ) {
break;
}
TimeUnit.NANOSECONDS.sleep(remainingTillOneMinuteOfSilence);
}
} @Override
public void onMessage(Message message) {
try {
ExampleCommon.handleMessage(message);
message.acknowledge();
System.out.println( "Acknowledged message " + message.getJMSMessageID() );
timeOfLastMessage = System.nanoTime();
} catch (JMSException e) {
System.err.println( "Error processing message: " + e.getMessage() );
e.printStackTrace();
}
}
}
}

https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/examples-sqs-messages.html
https://docs.amazonaws.cn/en_us/AWSSimpleQueueService/latest/SQSDeveloperGuide/code-examples.html

Amazon SQS 消息队列服务的更多相关文章

  1. NoSQL初探之人人都爱Redis:(3)使用Redis作为消息队列服务场景应用案例

    一.消息队列场景简介 “消息”是在两台计算机间传送的数据单位.消息可以非常简单,例如只包含文本字符串:也可以更复杂,可能包含嵌入对象.消息被发送到队列中,“消息队列”是在消息的传输过程中保存消息的容器 ...

  2. Redis作为消息队列服务场景应用案例

    NoSQL初探之人人都爱Redis:(3)使用Redis作为消息队列服务场景应用案例   一.消息队列场景简介 “消息”是在两台计算机间传送的数据单位.消息可以非常简单,例如只包含文本字符串:也可以更 ...

  3. 【转】NoSQL初探之人人都爱Redis:(3)使用Redis作为消息队列服务场景应用案例

    一.消息队列场景简介 “消息”是在两台计算机间传送的数据单位.消息可以非常简单,例如只包含文本字符串:也可以更复杂,可能包含嵌入对象.消息被发送到队列中,“消息队列”是在消息的传输过程中保存消息的容器 ...

  4. 【阿里云产品公测】消息队列服务MQS java SDK 机器人应用初体验

    [阿里云产品公测]消息队列服务MQS java SDK 机器人应用初体验 作者:阿里云用户啊里新人   初体验 之 测评环境 由于MQS支持外网访问,因此我在本地做了一些简单测试(可能有些业余),之后 ...

  5. 使用Redis作为消息队列服务场景应用案例

    一.消息队列场景简介 "消息"是在两台计算机间传送的数据单位.消息可以非常简单,例如只包含文本字符串:也可以更复杂,可能包含嵌入对象.消息被发送到队列中,"消息队列&qu ...

  6. 腾讯云分布式高可靠消息队列服务CMQ架构

    在分布式大行其道的今天,我们在系统内部.平台之间广泛运用消息中间件进行数据交换及解耦.CMQ是腾讯云内部自研基于的高可靠.强一致.可扩展分布式消息队列,在腾讯内部包括微信手机QQ业务红包.腾讯话费充值 ...

  7. Sping Boot入门到实战之实战篇(一):实现自定义Spring Boot Starter——阿里云消息队列服务Starter

    在 Sping Boot入门到实战之入门篇(四):Spring Boot自动化配置 这篇中,我们知道Spring Boot自动化配置的实现,主要由如下几部分完成: @EnableAutoConfigu ...

  8. 滴滴出行基于RocketMQ构建企业级消息队列服务的实践

    小结: 1. https://mp.weixin.qq.com/s/v6NM3UgX-qTI7yO1QPCJrw 滴滴出行基于RocketMQ构建企业级消息队列服务的实践 原创: 江海挺 阿里巴巴中间 ...

  9. 2.OpenStack-安装消息队列服务

    安装消息队列服务(安装在控制器上) yum install rabbitmq-server -y systemctl start mariadb.service 配置消息队列服务 systemctl ...

随机推荐

  1. Pytest权威教程02-Pytest 使用及调用方法

    目录 Pytest 使用及调用方法 使用python -m pytest调用pytest 可能出现的执行退出code 获取版本路径.命令行选项及环境变量相关帮助 第1(N)次失败后停止测试 指定及选择 ...

  2. vue列表拖拽排序功能实现

    1.实现目标:目标是输入一个数组,生成一个列表:通过拖拽排序,拖拽结束后输出一个经过排序的数组. 2.实现思路: 2.1是使用HTML5的drag功能来实现,每次拖拽时直接操作Dom节点排序,拖拽结束 ...

  3. 【洛谷】P2568 GCD

    前言 耻辱,我这个OI界的耻辱! 题目描述 给定整数N,求1<=x,y<=N且Gcd(x,y)为素数的数对(x,y)有多少对.输入格式  一个整数N输出格式答案输入输出样例  输入  4  ...

  4. 小程序在选择某一个东西的时候,可以用if,else 来做

    <view class='fake-select-item-text brand-selected' wx:if='{{selectedBrandName}}'> {{selectedBr ...

  5. 沸腾换热UDF【转载】

    #include "udf.h"    //包括常规宏 #include "sg_mphase.h"    // 包括体积分数宏 CVOF(C,T) #defi ...

  6. vue中如何动态添加readonly属性

    动态绑定input的readonly属性 1 <inpu :readonly="status ? false : 'readonly'"> status 为 false ...

  7. Python多线程与多进程详解

    进程,线程,协程https://blog.csdn.net/qq_23926575/article/details/76375337 多进程 https://www.cnblogs.com/lipij ...

  8. PHP如何解决网站大流量与高并发的问题(一)

    高并发的相关概念 在某个时间点,有多少个访问量 如果一个系统的日PV在千万以上,有可能是一个高并发的系统 QPS: 每秒钟请求或者查询的数量,在互联网领域,指每秒相应请求数(指HTTP请求) 吞吐量: ...

  9. 【Json】Json分词器

    package com.hy; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNo ...

  10. idea 如何新建一个Maven项目并且写第一个servlet

    使用idea已经有段时间了,但是一直没有自己亲自新建一个项目,从头开始写一个Servlet,今天就来学习一下,并且记一个笔记. 一. 1.首先,打开idea new-->Project 2.选择 ...