结合使用Springboot JMS 与 Amazon SQS 标准队列

1. 首先,来了解下JMS的一些概念AWS官网例子。关于SQS的使用总结可以参考:https://blog.csdn.net/BAStriver/article/details/103262276

2. 假设我们已经创建好一个springboot项目。那么,以下是个很简单的入门使用总结。

1) 先引入最新的依赖包:

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-jms</artifactId>
	<version>4.3.6.RELEASE</version>
</dependency>
<dependency>
	<groupId>com.amazonaws</groupId>
	<artifactId>amazon-sqs-java-messaging-lib</artifactId>
	<version>1.0.8</version>
</dependency>
<dependency>
	<artifactId>iam</artifactId>
	<groupId>software.amazon.awssdk</groupId>
	<version>2.3.7</version>
</dependency>

2) JMS配置类,初始化一些JMS配置:

package com.bas.configuration;

import com.amazon.sqs.javamessaging.ProviderConfiguration;
import com.amazon.sqs.javamessaging.SQSConnectionFactory;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.services.sqs.AmazonSQSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.support.destination.DynamicDestinationResolver;

import javax.jms.Session;

@Configuration
@EnableJms
@Profile({"stg", "dev", "prod"})
public class JmsConfiguration {

    private final AmazonSQSClientBuilder sqsClientBuilder;
    private final SQSConnectionFactory connectionFactory;

    public JmsConfiguration(@Value("${s3.regionKey}") String s3Region ) {
        sqsClientBuilder = AmazonSQSClientBuilder.standard()
                .withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
                .withRegion(s3Region);
        connectionFactory = new SQSConnectionFactory(new ProviderConfiguration(),this.sqsClientBuilder);
    }

    @Bean
    public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(){
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();

        factory.setConnectionFactory(this.connectionFactory);
        factory.setDestinationResolver(new DynamicDestinationResolver());

        //The values we provided to Concurrency show that we will create a minimum of 3 listeners that will scale up to 10 listeners
        factory.setConcurrency("3-10");

        /**
         *  SESSION_TRANSACTED
         *  CLIENT_ACKNOWLEDGE : After the client confirms, the client must call the acknowledge method of javax.jms.message after receiving the message. After the confirmation, the JMS server will delete the message
         *  AUTO_ACKNOWLEDGE : Automatic acknowledgment, no extra work required for client to send and receive messages
         *  DUPS_OK_ACKNOWLEDGE : Allow the confirmation mode of the replica. Once a method call from the receiving application returns from the processing message, the session object acknowledges the receipt of the message; and duplicate acknowledgments are allowed. This pattern is very effective when resource usage needs to be considered.
         */
        factory.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE);

        return factory;
    }
}

3) 以消费者为例:

package com.bas.configuration;

import com.amazon.sqs.javamessaging.message.SQSTextMessage;
import com.bas.service.SqsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.Message;

@Component
public class SqsConsumer {

    @Autowired
    private SqsService sqsService;

    @JmsListener(destination = "${sqs.queueName}")
    public void consumePortfolioMessage(Message message) {
        try {
            SQSTextMessage textMessage = (SQSTextMessage) message;
            sqsService.handleMessage(textMessage.getText());
            message.acknowledge(); // 删除消息
        } catch (JMSException e) {

        }

    }
}

因为设置的是客户端确认模式,所以要记得调用acknowledge()删除sqs消息。

 如果在消费消息的时候需要将消息转成实体对象,可以参考:springboot + aws +sqs + jms(简单托管消息队列)

@JmsListener(destination = "${sqs.queueName}")
public void test(@Payload final Message<MessageBody> message) {
	System.out.println("Listening {} in queue test"+ message.getPayload().getMessageId());
    // getMessageId() 是MessageBody的getter
}

 

1. 如果遇到:...jms.support.converter.MessageConversionException: Could not find type id property。

出现这个问题是因为JMS配置里面的转换器不能正常处理消息转成我们设置的MessageBody实体类。

2. 如果要中途关闭listener可以参考:https://segmentfault.com/n/1330000015554448

3. 如果遇到:...s3.model.S3Exception: Please reduce your request rate. (Service: S3, Status Code: 503...

出现这个问题是因为请求速率太频繁了超过了限制,可以参考:Amazon S3;状态代码:503;错误代码:SlowDown

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Amazon SQS(简单队列服务)是一种完全托管的消息队列服务,可用于在分布式应用程序之间传递消息。AWS SDK for Java 提供了 Amazon SQS 的开发工具包,使您可以轻松地与 Amazon SQS 进行交互并发送和接收消息。下面是使用 AWS SDK for Java 与 Amazon SQS 交互的步骤: 1. 配置 AWS 访问凭证:在使用 AWS SDK for Java 之前,您需要配置 AWS 访问凭证。访问凭证包括 AWS 访问密钥 ID 和秘密访问密钥。您可以使用 AWS 身份和访问管理(IAM)创建和管理这些凭证。 2. 创建 Amazon SQS 客户端:使用 AWS SDK for Java 创建 AmazonSQSClient 对象,以便与 Amazon SQS 服务进行交互。 ``` AmazonSQS sqs = AmazonSQSClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)) .withRegion(Regions.US_EAST_1) .build(); ``` 3. 创建队列使用 AmazonSQS 对象的 createQueue() 方法创建一个新的队列,并将其命名为您选择的名称。 ``` CreateQueueRequest create_request = new CreateQueueRequest(queueName); String myQueueUrl = sqs.createQueue(create_request).getQueueUrl(); ``` 4. 发送消息:使用 AmazonSQS 对象的 sendMessage() 方法向队列发送消息。 ``` SendMessageRequest send_msg_request = new SendMessageRequest() .withQueueUrl(myQueueUrl) .withMessageBody("hello world") .withDelaySeconds(5); sqs.sendMessage(send_msg_request); ``` 5. 接收消息:使用 AmazonSQS 对象的 receiveMessage() 方法从队列中接收消息。 ``` ReceiveMessageRequest receive_request = new ReceiveMessageRequest() .withQueueUrl(myQueueUrl) .withWaitTimeSeconds(20); List<Message> messages = sqs.receiveMessage(receive_request).getMessages(); for (Message message : messages) { // 处理消息 } ``` 6. 删除消息:使用 AmazonSQS 对象的 deleteMessage() 方法从队列中删除已处理的消息。 ``` String messageReceiptHandle = message.getReceiptHandle(); sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageReceiptHandle)); ``` 这些是使用 AWS SDK for Java 与 Amazon SQS 进行交互的基本步骤。您可以根据需要进行调整,以满足您的特定应用程序需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值