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. SpringData 简单的条件查询

    今天在写springdata条件查询时,JpaRepository的findOne方法,不知道是因为版本的原因还是其他原因,总是查询不出来数据 //springdata jpa版本为1.5.15,配置 ...

  2. MyBatis项目配置案例详解与Web下的增删改查实现[附项目源码]

    MyBatis项目案例 项目图示: 项目源码地址:https://github.com/JluTiger/mybatispro 1.项目功能 项目案例:后台管理系统用户数据维护平台 所有用户数据查询 ...

  3. 【随记】安装SQL Server 2008 R2 提示创建usersettings/microsoft.sqlserver.configuration.landingpage.properties.se

    在安装SQL Server 2008 R2 提示创建usersettings/microsoft.sqlserver.configuration.landingpage.properties.se.. ...

  4. Hbase监控指标项

    名词解释 JMX:Java Management Extensions,用于用于Java程序扩展监控和管理项 GC:Garbage Collection,垃圾收集,垃圾回收机制 指标项来源 主机名 u ...

  5. 找到树中指定id的所有父节点

    const data = [{ id: 1, children: [{ id: 2, children: [{ id: 3, }, { id: 4, }], }], }, { id: 5, child ...

  6. Windows 实例远程桌面报错“没有远程桌面授权服务器可以提供许可证”

    参考阿里云帮助文档: https://help.aliyun.com/knowledge_detail/40859.html?spm=5176.10695662.1996646101.searchcl ...

  7. 腾讯云CENTOS7安装MSSQL2017

    腾讯云CENTOS7安装MSSQL2017 mkdir -p /opt/sqlserver2017cd /opt/sqlserver2017/ 下载离线包:wget https://packages. ...

  8. polarssl rsa & aes 加密与解密<转>

    上周折腾加密与解密,用了openssl, crypto++, polarssl, cyassl, 说起真的让人很沮丧,只有openssl & polarssl两个库的RSA & AES ...

  9. nmcli 配置ip

    配置ip: nmcli connection modify 'Wired connection 1' connection.autoconnect yes ipv4.method manual ipv ...

  10. SSH项目中使用struts-tags报错According to TLD or attribute directive in tag file, attribute test does not accept any expressions

    在运行struts2标签页面时报错,代码如下:<%@ page language="java" pageEncoding="gbk"%><%@ ...