Проблема
Мои коллеги (Том Purcell и Род Biresch) и сам работает на демо — приложение для
Chariot Solutions »
Emerging Technologies для предприятияконференции и необходимость транспортного компонента для упрощения доступа к Amazon SQS возникла. Мы решили использовать FUSE ESB (ServiceMix) 4 в качестве платформы интеграции сервисов для демонстрационного приложения, и, зная, что Apache Camel очень хорошо работает с ServiceMix, мы решили использовать его для нужд маршрутизации и преобразования.
В настоящее время ни ServiceMix, ни Camel не предоставляют компонента для доступа к Amazon SQS. Помимо этого ограничения, оставшиеся возможности, предоставляемые этими продуктами, сделали его отличным выбором для демонстрационного приложения.
Чтобы узнать больше о демонстрационном приложении, пожалуйста, посетите
блог Тома Пурселла . Я также рекомендую посетить презентацию Тома Перселла под названием
«Автобус в облаках»где он будет говорить о случаях использования Could Computing и о том, как технологии Open Source Integration могут помочь решить проблемы, возникающие при интеграции с деловыми партнерами.
Другой важной частью в производственных приложениях является управление и мониторинг. Чтобы узнать больше о том, как контролировать это приложение, пожалуйста, посетите
блог Рода Биреша .
Решение
Apache Camel позволяет относительно легко создавать собственные компоненты, поэтому следующим логическим шагом было попытаться создать его. Увидев API-интерфейс Typica Дейва Кавана
в действии и то, насколько просто он обеспечивает связь с SQS, мы решили попробовать создать такой компонент Camel, используя этот API в качестве основы.
Компонент Camel Amazon SQS
Основная идея заключается в создании компонента, который можно использовать следующим образом:
<camel:route>
<camel:from uri="file:data-in" />
<camel:convertBodyTo type="java.lang.String" />
<camel:to uri="sqs:sqsProducer?accessId=...&secretKey=...&queueName=dataQueue"/>
</camel:route>
<camel:route>
<camel:from
uri="sqs:sqsConsumer?accessId=...&secretKey=...&queueName=dataQueue" />
<camel:to uri="file:data-out" />
</camel:route>
В приведенном выше примере показан маршрут Camel, который отправляет данные, найденные в файлах, помещенных в каталог данных, в очередь SQS с именем «dataQueue». В URI «sqs: sqsProducer? AccessId = ….» протокол «sqs» сообщит Camel, какой компонент для настройки и атрибуты будет сопоставлен со свойствами либо конечной точки, либо класса Producer. Документацию по написанию Camel Components можно найти здесь. Давайте погрузимся в дизайн компонента Camel SQS. Основные шаги для написания Camel Component:
- Напишите POJO, который реализует интерфейс компонента. Самый простой подход — просто извлечь из DefaultComponent. В нашем случае класс SQSComponent был создан. Этот класс расширяет DefaultComponent.
- To support auto-discovery of your component add a file to META-INF/services/org/apache/camel/component/sqs
where ‘sqs’ is the URI scheme for your component and any related endpoints created on the fly. The sqs file will contain the class attribute with the name of Class that implements the Component:
class=com.chariotsolutions.soalab.camel.component.sqs.SQSComponent
The Camel SQS Component is composed of the following artifacts:
The SQSComponent Class
This class serves as factory of Endpoints. When the component is being configured by Camel, the method of the createEndpoint is called. This method creates and configures the Endpoint (SQSEndpoint).
The SQSEndpoint Class
This class serves as a factory for Producers, Consumers, and Exchanges.
After the SQSComponent.createEndpoint is execute, an instance of the class SQSEndoint is created.
This class contains the properties used by the SQSConsumer class. These properties are:
private String accessId;
private String secretKey;
private String queueName;
This class extends ScheduledPollEndpoint and is used to create instances of the SQSProducer and SQSConsumer. The use of the ScheduledPollEndpoint is with the intention to use polling facilities it provides to query the SQS Queue at a specified time intervals.
The SQSConsumer Class
This class extends the ScheduledPollConsumer class to indicate that it will be excueted in poll intervals.
The poll intervals are configured in the Component URI using the consumer.initialDelay and consumer.delay attributes like so:
<from uri="sqs:sqsConsumer?...&consumer.initialDelay=1000&consumer.delay=25000" />
The poll() will be executed based on the configuration specified above.This method uses the Typica API to interact with the Amazon SQS Web services. If a message was found in the SQS Queue, it will e forward to the handleMessage. This method will set the message in a wrapper class called SQSObject, place it in the SQSExchange and send it flow of the route using the synchronous Processor by default. The attribute asyncProcess=true would cause it to use the AsyncProcess.
The SQSProducer Class
This class extends the DefaultProducer class. It processes the message coming from the Camel flow and sends it to the SQS queue, then it sets the assigned message id to the SQSObject, which is later added to the SQSExchange in case other components need it down the road.
The SQSExchange Class
This The base message exchange interface providing access to the request, response and fault instances.
The SQSObject Class
This is convenient POJO that wraps the payload and properties coming from the SQS Queue.
Taking the Camel SQS Component For A Ride
To see the Camel SQS Component in action, I created a small sample application.
The sample application can be found in here. Here are the steps to build and run the application:
- If you haven’t already done so, create an Amazon SQS account using the «Sign Up» button in this page.
- Extract the sample code to a directory of your choice. For example, /tmp/sqs-sample. You should see 2 directories in there, camel-sqs (camel sqs component) and camel-sqs-route (sample camel route).
- Navigate to the camel-sqs directory and build the code using: mvn clean install
- Navigate to the camel-sqs-route directory.
- Edit the file src/main/resources/aws.properties. Specify aws.accessId and aws.secretKey for your Amazon SQS account.
- Edit the file src/main/resources/META-INF/spring/camel-context.xml. Find the file endpoints and modify them to point to the directories of your choice. The File-In endpoint is where you would supply the data files to be sent to the SQS queue. The File-Out endpoint is the directory where the files containing the contents of the SQS queue will be placed on.
- Build the code using: mvn clean install
- Run the code using: mvn camel:run
- You should be able to place your sample text files directory pointed by the File-In endpoint. After a few seconds the output files will be placed in directory pointed by File-Out.
Conclusion
Amazon SQS combined with ServiceMix and Camel are a great platform for building your IaaS (Infrastructure as a Service) projects. Hopefully future versions of Apache Camel will include such component. The Camel CAMEL-1432 JIRA issue has been created for this reason.Happy Cloud Computing!
Recommended Sites
Tom Purcell’s Blog
Rod Biresch’s Blog
Amazon SQS
FUSE ESB (ServiceMix) 4
Apache Camel
Chariot Solutions