mda with spring 11-18-10
TRANSCRIPT
-
8/6/2019 Mda With Spring 11-18-10
1/43
Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Message Driven
Architecture with Spring
Mark Fisher, SpringSource/VMware
-
8/6/2019 Mda With Spring 11-18-10
2/43
2Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Agenda
Events Messaging
Polling
Scheduling
Pipes and Filters
Enterprise Integration Patterns
Q&A
-
8/6/2019 Mda With Spring 11-18-10
3/43
Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Events
?
?
-
8/6/2019 Mda With Spring 11-18-10
4/43
4Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Sending ApplicationEvents
publicclass MyEventPublisher implements ApplicationEventPublisherAware { privatevolatile ApplicationEventPublisher publisher; publicvoid setApplicationEventPublisher(ApplicationEventPublisher aep) { this.publisher = aep;
}
publicvoid send(String text) {Assert.notNull(this.publisher, no publisher available); this.publisher.publishEvent(new MyEvent(text));
}
}
1. Implement the callback to have the publisher injected by the container.
2. Define the bean, and use the publisher to send events at runtime.
-
8/6/2019 Mda With Spring 11-18-10
5/43
5Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Receiving ApplicationEvents
publicclass MyEventListener implements ApplicationListener {privatefinal Log log = LogFactory.getLog(this.getClass());publicvoid onApplicationEvent(ApplicationEvent event) {this.log.info("received event: " + event);}
}
1. Implement the ApplicationListener interface.
2. Define the bean, and it will be invoked at runtime when Events occur.
-
8/6/2019 Mda With Spring 11-18-10
6/43
6Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Filtering Event Types
publicclass FooEventListener implements ApplicationListener {privatefinal Log log = LogFactory.getLog(this.getClass());publicvoid onApplicationEvent(FooEvent event) {this.log.info("received FOO event: " + event);}
}
1. Implement the ApplicationListener interface with a parameterized type.
2. Define the bean, and it will be invoked at runtime when that type of Event occurs.
-
8/6/2019 Mda With Spring 11-18-10
7/43Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Messaging
-
8/6/2019 Mda With Spring 11-18-10
8/438Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Sending JMS Messages
publicclass MessageSender { @Autowiredprivate volatile JmsTemplate jmsTemplate;
publicvoid send(String message) { this.jmsTemplate.convertAndSend("example.queue", message);}}
1. Inject an instance of Spring's JmsTemplate.
2. Provide the JMS ConnectionFactory in the JmsTemplate bean definition.
...
-
8/6/2019 Mda With Spring 11-18-10
9/439Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Receiving JMS Messages
publicclass MyListener {privatefinal Log log = LogFactory.getLog(this.getClass());
publicvoid log(String message) { this.log.info("received: " + message);}}
1. Define a listener-container within the context.
2. Point to any POJO to implicitly create a MessageListenerAdapter.
-
8/6/2019 Mda With Spring 11-18-10
10/4310Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Spring AMQP
Similar to Spring's JMS support Does not hide AMQP behind JMS
Currently in 1.0 milestone phase
Exchanges Where producers send Messages May also send a routing key
Queues Where consumers receive Messages A named FIFO buffer
Bindings Exchanges route to queues Queues bind with routing keys/patterns
-
8/6/2019 Mda With Spring 11-18-10
11/4311Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Sending and ReceivingAMQP Messages
publicclass MessageSender { @Autowiredprivate volatile AmqpTemplate amqpTemplate;
publicvoid send(String message) { this.amqpTemplate.convertAndSend( "myExchange", "some.routing.key", message);}}
1. Use AmqpTemplate instead of JmsTemplate (accepts exchange and routingKey).
2. Nothing changes on the listener side (just a POJO).
publicclass MyListener {privatefinal Log log = LogFactory.getLog(this.getClass());
publicvoid log(String message) { this.log.info("received: " + message);}}
-
8/6/2019 Mda With Spring 11-18-10
12/43Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Polling
-
8/6/2019 Mda With Spring 11-18-10
13/4313Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Lifecycle Management
publicinterface Lifecycle {void start();void stop();boolean isRunning();}
Spring's Lifecycle interface provides basic support for any background task.
publicinterface SmartLifecycle extends Lifecycle, Phased {boolean isAutoStartup();void stop(Runnable callback);}
publicinterface Phased {int getPhase();}
SmartLifecycle adds auto-startup and graceful shutdown capabilities.
-
8/6/2019 Mda With Spring 11-18-10
14/4314Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Task Execution
publicclass FilePoller implements Lifecycle { @Autowired @Qualifier("threadPool")private volatile Executor executor; publicvoid start() { this.executor.execute(new Runnable() { publicvoid run() { while (!this.stopRequested) { // poll a directory by calling listFiles()
// send the list of Files to a handler }}});}...
Spring provides a TaskExecutor whose signature matches Executor.
Several implementations are available: Threads can be managed, pooled, etc.
-
8/6/2019 Mda With Spring 11-18-10
15/4315Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
@Async
publicclass FilePoller implements Lifecycle { @Async publicvoid start() { while (!this.stopRequested) { // poll a directory by calling listFiles()// send the list of Files to a handler }}...}
The @Async annotation implicitly adds the Executor support.
-
8/6/2019 Mda With Spring 11-18-10
16/43Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Scheduling
-
8/6/2019 Mda With Spring 11-18-10
17/43
17Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Task Scheduler and Trigger
publicinterface TaskScheduler {ScheduledFuture schedule(Runnable task, Trigger trigger);ScheduledFuture scheduleAtFixedRate(Runnable task, long period);ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay);...}
Spring's TaskScheduler and Trigger provide an abstraction for scheduling tasks.
publicinterface Trigger {Date nextExecutionTime(TriggerContext triggerContext);
} publicinterface TriggerContext {Date lastScheduledExecutionTime();Date lastActualExecutionTime();Date lastCompletionTime()}
Trigger implementations include: PeriodicTrigger CronTrigger
-
8/6/2019 Mda With Spring 11-18-10
18/43
18Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Task Scheduling
publicclass FilePoller implements Lifecycle { @Autowired @Qualifier("scheduler")private volatile TaskScheduler scheduler; // other properties, e.g. 'task' and 'trigger' publicvoid start() { this.task = this.scheduler.schedule(task, trigger);} publicvoid stop() { if (this.task != null ) { this.task.cancel(true); }}...}
TaskScheduler supports recurring, cancelable tasks.
As with TaskExecutor, Threads can be managed, pooled, etc.
-
8/6/2019 Mda With Spring 11-18-10
19/43
19Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
@Scheduled
publicclass FilePoller { @Scheduled(cron="*/5 * 9-17 * * ?") publicvoid poll() { // poll and send Files to a handler}}
The @Scheduled annotation implicitly adds the TaskScheduler support.
Spring also provides as an alternative to annotations.
-
8/6/2019 Mda With Spring 11-18-10
20/43
20Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
@Scheduled as Meta-annotation
@Scheduled(cron="${schedules.daytime}")@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public@interface Daytime {} @Daytime publicvoid poll() { // poll and send Files to a handler}
schedules.daytime=*/5 * 9-17 * * ?
-
8/6/2019 Mda With Spring 11-18-10
21/43
Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Pipes and Filters
-
8/6/2019 Mda With Spring 11-18-10
22/43
22Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Message
Payload can be any object
Header values are stored in a Map
Headers
Payload
-
8/6/2019 Mda With Spring 11-18-10
23/43
23Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Message and Headers
public interface Message {
MessageHeaders getHeaders();
T getPayload();
}
public interface Message {
MessageHeaders getHeaders();
T getPayload();
}
Message m1 = MessageBuilder.withPayload(foo).setHeader(itemId, 123).build();
Message m2 = MessageBuilder.fromMessage(m1).setHeader(itemId, 456).build();
Message m1 = MessageBuilder.withPayload(foo).setHeader(itemId, 123).build();
Message m2 = MessageBuilder.fromMessage(m1).setHeader(itemId, 456).build();
MessageHeaders headers = message.getHeaders();
long timestamp = headers.getTimestamp();
String value = headers.get(someKey, String.class);
MessageHeaders headers = message.getHeaders();
long timestamp = headers.getTimestamp();
String value = headers.get(someKey, String.class);
-
8/6/2019 Mda With Spring 11-18-10
24/43
24Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Message Channel
Decouples Producers from Consumers
Provides extension point for interceptors
May be Point-to-Point
Or Publish/Subscribe
-
8/6/2019 Mda With Spring 11-18-10
25/43
25Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Message Channel Types
-
8/6/2019 Mda With Spring 11-18-10
26/43
26Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Sending Messages
public interface MessageChannel { boolean send(Message message); boolean send(Message message, long timeout);}
public interfaceMessageChannel { boolean send(Message message); boolean send(Message message, long timeout);} MessagingTemplate template = new MessagingTemplate();
template.send(someChannel, message);
template.send(fooChannel, message);
template.convertAndSend(someChannel, hello);
template.convertAndSend(fooChannel, someObject);
template.setSendTimeout(5000);
template.setDefaultChannel(someChannel);
template.convertAndSend(someObject);
MessagingTemplate template = new MessagingTemplate();template.send(someChannel, message);
template.send(fooChannel, message);
template.convertAndSend(someChannel, hello);
template.convertAndSend(fooChannel, someObject);
template.setSendTimeout(5000);
template.setDefaultChannel(someChannel);
template.convertAndSend(someObject);
-
8/6/2019 Mda With Spring 11-18-10
27/43
27Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Gateway Proxy
public interface MyGateway { void send(String text);
String send(@Payload Foo foo, @Header(bar) String s);
}
public interfaceMyGateway { void send(String text);
String send(@Payload Foo foo, @Header(bar) String s);
}
-
8/6/2019 Mda With Spring 11-18-10
28/43
28Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Message Publishing Interceptor
Non-invasive, AOP-based implementation
Uses SpEL for generating payload and headers
@Publisher(channel="confirmations") // payload = #return
public String createBooking(BookingRequest request) {...
}
@Publisher(payload="#args.bookingId", channel="cancellations")public void cancelBooking(String bookingId) {
...}
-
8/6/2019 Mda With Spring 11-18-10
29/43
29Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
@Publisher as a Meta-Annotation
@Publisher(channel="auditChannel")public @interface Audit {}
Define a custom annotation
Apply to methods, no channel required
@Auditpublic UsercreateUser(String name) {...}
@Auditpublic UserdeleteUser(long userId) {...}
-
8/6/2019 Mda With Spring 11-18-10
30/43
30Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Receiving Messages
Inversion of Control Endpoints delegate to Spring-managed objects
Framework handles message reception andmethod invocation
Similar but more abstract than Spring JMS
Clean separation of Code and Configuration
-
8/6/2019 Mda With Spring 11-18-10
31/43
31Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Message Endpoint
Producers send Messages to a MessageChannel
Depending on their type, Message Channelsmay have Polling Consumers
Or Event-Driven Consumers
-
8/6/2019 Mda With Spring 11-18-10
32/43
Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Enterprise IntegrationPatterns
-
8/6/2019 Mda With Spring 11-18-10
33/43
33Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Message Endpoint Types
Transformer Convert payload or modify headers
Filter
Discard messages based on boolean evaluation
Router
Determine next channel based on content
Splitter
Generate multiple messages from one Aggregator
Assemble a single message from multiple
-
8/6/2019 Mda With Spring 11-18-10
34/43
34Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Expression Language Support
Alternative option for ref/method in endpoints
Mapping between Messages and Methods
public void createAccount(
@Payload("firstName") String firstName,@Payload("lastName") String lastName,@Header("userInfo.account.id") String accountId) {...}
-
8/6/2019 Mda With Spring 11-18-10
35/43
35Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Groovy Support
Another option for endpoints
-
8/6/2019 Mda With Spring 11-18-10
36/43
36Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Channel Adapters andMessaging Gateways
JMS
AMQP
TCP
UDP
File/FTP/SFTP
RMI
RSS
HTTP (REST)
WS (SOAP/POX)
Mail (POP3/IMAP/SMTP)
JDBC
XMPP
Twitter
Spring Events
-
8/6/2019 Mda With Spring 11-18-10
37/43
37Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Channel Adapters (one-way)
http://inbound-channel-adapter/http://inbound-channel-adapter/ -
8/6/2019 Mda With Spring 11-18-10
38/43
38Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Gateways (request-reply)
-
8/6/2019 Mda With Spring 11-18-10
39/43
39Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
XML Support
XPath Router XPath Splitter
XPath Transformer
XPath Header Enricher XSLT Transformer
OXM Marshalling Transformer
OXM Unmarshalling Transformer
Spring Integration and
-
8/6/2019 Mda With Spring 11-18-10
40/43
40Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Spring Integration andOther Spring Projects
Spring Integration for .NET Spring AMQP: Channel Adapters
Spring BlazeDS (Flex): Messaging Adapter
Spring Batch: Jobs Events Spring Web Services: Gateways
Spring Security: Channel Interceptor
Spring Roo: Addon SpringSource Tool Suite
-
8/6/2019 Mda With Spring 11-18-10
41/43
41Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
STS Visual Editor
-
8/6/2019 Mda With Spring 11-18-10
42/43
Copyright 2005-2010 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Demos
-
8/6/2019 Mda With Spring 11-18-10
43/43
Links
Spring Framework Documentation http://static.springsource.org/spring/docs/3.0.x
Spring AMQP
http://www.springsource.org/spring-amqp
Spring Integration http://www.springsource.org/spring-integration
Enterprise Integration Patterns
http://enterpriseintegrationpatterns.com
Sample Code http://git.springsource.org/spring-integration/samples