Чтобы проиллюстрировать это, рассмотрим простую систему, которая просто принимает сообщение и отправляет его с заглавной буквы, назовите его Echo Gateway:
|
1
2
3
|
public interface EchoGateway { String echo(String message);} |
и тест для этого:
|
1
2
3
4
5
|
@Test public void testEcho() { String response = echoGateway.echo('Hello'); assertThat(response, is('HELLO')); } |
Пока это звучит просто, реализация, использующая пружинную интеграцию, будет принимать «сообщение» и «преобразовывать» его путем преобразования в верхний регистр и возврата расширенного сообщения.
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
|
<?xml version='1.0' encoding='UTF-8'?> xsi:schemaLocation=' http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration-2.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd'> <channel id='requestChannel'/> <gateway id='echoGateway' service-interface='rube.simple.EchoGateway' default-request-channel='requestChannel' /> <transformer input-channel='requestChannel' expression='payload.toUpperCase()' /> </beans:beans> |
Работает красиво !!
Прелесть Spring Integration в том, что даже если сценарий Integration становится сложным, фасад, который он представляет обратно приложению, продолжает оставаться простым,
Рассмотрим сценарий интеграции Rube Goldberg :
Сначала диаграмма для описания извилистого потока:
Итак, что именно это делает:
- Он принимает сообщение этого типа — «привет из весны Integ»,
- разбивает его на отдельные слова (привет, от, весна, целое),
- отправляет каждое слово в очередь ActiveMQ,
- из очереди фрагменты слова выбираются обогащателем, чтобы использовать каждое слово с заглавной буквы,
- помещение ответа обратно в очередь ответов,
- Он подобран, переупорядочен на основе оригинальной последовательности слов,
- объединены обратно в предложение («ПРИВЕТ ОТ ВЕСНОЙ ИНТЕГ») и
- вернулся к заявке.
Вот как будет выглядеть конфигурация Spring Integration для такого потока:
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
<?xml version='1.0' encoding='UTF-8'?> xsi:schemaLocation=' http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration-2.1.xsd http://www.springframework.org/schema/integration/jms http://www.springframework.org/schema/integration/jms/spring-integration-jms-2.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd'> <beans:import resource='broker.xml'/> <channel id='requestChannel'> <queue/> </channel> <channel id='responseChannel'> <queue/> </channel> <gateway id='echoGateway' service-interface='rube.complicated.EchoGateway' default-request-channel='requestChannel' default-reply-channel='responseChannel' default-reply-timeout='5000' /> <channel id='toJmsOutbound'/> <splitter input-channel='requestChannel' output-channel='toJmsOutbound' expression='payload.split('\s')'> </splitter> <channel id='sequenceChannel'> </channel> <int-jms:outbound-gateway request-channel='toJmsOutbound' reply-channel='sequenceChannel' request-destination='amq.outbound' extract-request-payload='true' /> <channel id='enhanceMessageChannel'/> <channel id='toReplyQueueChannel'/> <int-jms:inbound-gateway request-channel='enhanceMessageChannel' request-destination='amq.outbound' reply-channel='toReplyQueueChannel'/> <transformer input-channel='enhanceMessageChannel' expression='(payload + '').toUpperCase()' output-channel='toReplyQueueChannel'/> <resequencer input-channel='sequenceChannel' output-channel='aggregateChannel' release-partial-sequences='false'></resequencer> <aggregator input-channel='aggregateChannel' output-channel='responseChannel' expression='T(com.google.common.base.Joiner).on(' ').join(![payload].toArray())'/> <poller id='poller' fixed-delay='500' default='true'/> </beans:beans> |
В этом потоке столько сложностей (отсюда и Рубе Голдберга), однако фасад, который Spring Integration предоставляет приложению, продолжает оставаться очень простым.
|
1
2
3
4
5
6
7
|
@Test public void testEcho() throws Exception{ String amessage = 'Hello from Spring Integration'; String response = echoGateway.echo(amessage); assertThat(response, is('HELLO FROM SPRING INTEGRATION')); } |
Это, на мой взгляд, суть Spring Integration
У меня есть github-репозиторий с этим кодом по адресу https://github.com/bijukunjummen/rg-si.git.
Ссылка: Rube Goldberg Spring Integration от нашего партнера JCG Биджу Кунджуммен в блоге « все и вся» .
