最近AWS公布了新的客户端库,它实现了JMS 1.1规范 ,并使用他们的简单队列服务 (SQS)作为JMS提供者 (见杰夫·巴尔的帖子在这里 )。 在我的文章中,我将向您展示如何设置Maven项目以使用Spring Framework来使用该库。
我们将执行以下步骤:
- 在AWS管理控制台中创建队列
- 在机器上设置您的AWS凭证
- 设置您的Maven项目
- 创建Spring配置
- 创建Java文件以产生和接收消息
这篇文章将仅显示SQS可能性的一些基本用法,但应该足以帮助您入门。 我假设您已经创建了AWS账户 ,并且熟悉Maven和基本的Spring设置。
在AWS管理控制台中创建队列
第一步是创建队列,以便我们可以在程序中使用它。 我向您展示了如何使用管理控制台创建队列,但是您也可以通过编程方式创建必要的队列。
转到管理控制台时,可以选择SQS页面,然后单击“创建新队列”按钮:
输入队列名称,并单击“创建队列”按钮,以接受当前的默认设置:
在机器上设置您的AWS凭证
为了能够使用Java SDK访问您的AWS资料,最简单的方法是在用户的主目录中创建一个“ credentials.proeprties”文件。 在〜/ .aws / credentials(对于Windows用户为C:\ Users \ USER_NAME \ .aws \ credentials)处创建凭据文件,并在将大写的值替换为您自己的值之后,保存以下行。
[default]
aws_access_key_id = YOUR_ACCESS_KEY_ID
aws_secret_access_key = YOUR_SECRET_ACCESS_KEY
设置您的Maven项目
使用Maven设置项目时,可以将以下依赖项添加到pom中,以便能够在Spring 4中使用AWS SQS:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>net.pascalalma.aws</groupId><artifactId>sqs-client</artifactId><version>1.0-SNAPSHOT</version><properties><version.spring>4.1.5.RELEASE</version.spring></properties><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>${version.spring}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${version.spring}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jms</artifactId><version>${version.spring}</version></dependency><dependency><groupId>com.amazonaws</groupId><artifactId>amazon-sqs-java-messaging-lib</artifactId><version>1.0.0</version><type>jar</type></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency></dependencies>
</project>
创建Spring配置
在第一个示例中,我将使用一个简单的MessageProducer和MessageConsumer类,其中生产者将消息放入队列,而使用者将从队列中读取一条消息。 这是模型是下文称要通过AWS作为一个“同步”的呼叫。 Spring配置如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"><context:component-scan base-package="net.pascalalma.aws.sqs"></context:component-scan><bean id="credentialsProviderBean" class="com.amazonaws.auth.DefaultAWSCredentialsProviderChain"/><bean id="connectionFactoryBuilder" class="com.amazon.sqs.javamessaging.SQSConnectionFactory$Builder"><property name="regionName" value="eu-west-1"/><property name="numberOfMessagesToPrefetch" value="5"/><property name="awsCredentialsProvider" ref="credentialsProviderBean"/></bean><bean id="connectionFactory" class="com.amazon.sqs.javamessaging.SQSConnectionFactory"factory-bean="connectionFactoryBuilder"factory-method="build"/><bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"><property name="connectionFactory" ref="connectionFactory"/><property name="defaultDestinationName" ref="queueName"/></bean><bean id="queueName" class="java.lang.String"><constructor-arg value="DefaultDemoQueue"/></bean>
</beans>
创建Java文件以产生和接收消息
最后一步是创建必要的Java文件。 我认为它们足够简单且易于解释,因此我仅在此处显示源代码。 首先,我们有MessageProducer,它在执行消息时将消息放入队列中:
package net.pascalalma.aws.sqs;import org.apache.log4j.Logger;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;@Service("myMessageProviderService")
public class MyMessageProvider {final static Logger logger = Logger.getLogger(MyMessageProvider.class);@Resource(name = "jmsTemplate")private JmsTemplate jmsTemplate;public void sendMessage(final String txt) {logger.debug(String.format("Sending message with txt: %s", txt));jmsTemplate.send(new MessageCreator() {public Message createMessage(Session session) throws JMSException {final TextMessage msg = session.createTextMessage(txt);return msg;}});logger.debug("Message sent ");}
}
接下来是MessageConsumer,在此示例中,MessageConsumer在执行时仅从队列中读取一条消息:
package net.pascalalma.aws.sqs;import org.apache.log4j.Logger;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;@Service("myMessageConsumerService")
public class MyMessageConsumer {final static Logger logger = Logger.getLogger(MyMessageConsumer.class);@Resource(name = "jmsTemplate")private JmsTemplate jmsTemplate;public void readMessage() throws JMSException {logger.debug("Reading message");Message msg = jmsTemplate.receive();if (msg instanceof TextMessage) {TextMessage txtmsg = (TextMessage) msg;logger.info(String.format("Received text: %s", txtmsg.getText()));}logger.debug(msg.getClass());logger.info("Done");}
}
最后是Main类,它读取Spring配置并运行Producer和Consumer:
package net.pascalalma.aws.sqs;import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import javax.jms.JMSException;public class SpringMain {final static Logger logger = Logger.getLogger(SpringMain.class);public static void main(String[] args) {//Build application context by reading spring-config.xmlApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"application-context.xml"});//Get an instance of ProductService class;MyMessageProvider prdSvc = (MyMessageProvider) ctx.getBean("myMessageProviderService");MyMessageConsumer conSvc = (MyMessageConsumer) ctx.getBean("myMessageConsumerService");//Call getProduct method of ProductServiceprdSvc.sendMessage("This is a test");try {conSvc.readMessage();} catch (JMSException e) {logger.error(e);}}
}
当运行Main类时,一切正常时,您将看到以下输出:
2015-03-29 10:26:39 DEBUG net.pascalalma.aws.sqs.MyMessageProvider(28) - Sending message with txt: This is a test
2015-03-29 10:26:41 DEBUG net.pascalalma.aws.sqs.MyMessageProvider(35) - Message sent
2015-03-29 10:26:41 DEBUG net.pascalalma.aws.sqs.MyMessageConsumer(24) - Reading message
2015-03-29 10:26:41 INFO net.pascalalma.aws.sqs.MyMessageConsumer(29) - Received text: This is a test
2015-03-29 10:26:41 DEBUG net.pascalalma.aws.sqs.MyMessageConsumer(32) - class com.amazon.sqs.javamessaging.message.SQSTextMessage
2015-03-29 10:26:41 INFO net.pascalalma.aws.sqs.MyMessageConsumer(33) - DoneProcess finished with exit code 0
翻译自: https://www.javacodegeeks.com/2015/04/using-aws-sqs-as-jms-provider-with-spring.html