,

In this post, I’m going to walk you through using Spring Boot to setup a Hello World example using Spring Integration and ActiveMQ. We’ll configure Spring Integration to listen on a ActiveMQ queue. For fun, I’ll use Spock to place a message on the queue, and we can watch Spring Integration receive the JMS Message and print a message to the console.

Spring Boot Project Setup

Spring Initializr

Using IntelliJ to create a new project, I’ll select the option to use the Spring Initializr to create my new Spring Boot project. The IntellIj dialog makes it easy to create a Spring Boot project.

In this case, I’m selecting the latest version of Spring Boot (1.3.0.M3) at the time of writing, and the option for Spring Integration.

IntelliJ and Spring Initializr

After completing the steps in IntelliJ, I’ll have a fresh Maven project to work with for this example.

Spring Integration and ActiveMQ Dependencies

Spring Boot does a pretty good job of bringing in the basic dependencies. Using the Maven support in IntelliJ, we can look at Maven dependencies for our project. You can see that via the Spring Boot artifacts, we’re bringing in the basic dependencies for Spring Integration.

Spring Boot and Spring Integration maven dependencies in IntelliJ

 

At the time of writing, the Spring Initializr does not support ActiveMQ directly. I didn’t look to see if the Spring Boot team defined a Maven artifact for this or not. But, it’s simple enough to add the dependencies we will need for Spring Integration and ActiveMQ.

Notice how I have not added version information to the dependencies? That gets inherited from the parent Spring Boot Maven POM.

ActiveMQ Spring Boot Configuration

Like many other things, Spring Boot makes our task of configuring ActiveMQ easier. For the purposes of our example, we want to use an embedded ActiveMQ broker. This is common to use when developing Spring projects which use ActiveMQ. Often when developing enterprise applications using Spring, you will use a ActiveMQ embedded broker for development  and then have a configuration to use IBM’s MQSeries in production.

ActiveMQ Broker

By just having ActiveMQ on our build path, Spring Boot will automatically set up a ActiveMQ broker. We need to set a couple properties to make it an in memory broker, without connection pooling. We can do this by setting two properties for Spring Boot.

application.properties

ActiveMQ Queue Configuration

We also need to setup a queue for our example. We can do this in a Spring Java Configuration class as follows.

ActiveMQConfig.java

This is all we need to do to configure ActiveMQ for our example. Spring Boot will take care of the rest.

Spring Integration Configuration

Spring Integration JMS Channel Adapter

Spring Integration comes with a number of different channel adapters. In this case, we need to configure a JMS channel adapter. This will serve as a transparent bridge between Spring Integration Messaging and JMS Messaging.

In the Spring Integration XML configuration below, I’ve defined a Spring Integration JMS channel adapter. The destination property is set to the name of the ActiveMQ queue bean we defined above. (When using Spring Java configuration, the bean reference becomes is inherited from the method name in the configuration class.) I’ve also added a Spring Integration channel to the configuration.

This acts as a bridge, messages coming from the JMS queue will get sent the the Spring Integration channel, and messages sent to the Spring Integration channel will get passed along to the JMS queue.

si-config.xml

Say Hello Service

We’ll use a simple service for our example today. Its a Spring Service component, which simply takes a string in and prints it out to the console.

SayHelloService.java

Spring Integration Service Activator Configuration

Next we need to add a Spring Integration Service Activator. This is what Spring Integration will use to process the message. We just need to add the following to our Spring Integration XML file.

/resources/spring/si-config.xml

Spring Boot Configuration

We need to tell Spring Boot about the Spring Integration XML configuration file. We can to this by adding an ImportResource  annotation to the Spring Boot application class file as follows.

HelloWorldSiActivemqApplication.class

Spock Configuration

Maven Dependencies

To enable Spock support add the following dependencies to your Maven pom file.

Maven Compiler Plugin

Spock test classes are written in Groovy. You will need to add a Groovy compiler to your Maven build. I like to use the Groovy Eclipse Compiler. Add the following plugin to your build plugins.

Sending a JMS Message Using Spock

There’s a lot of different ways to send a JMS message. I chose to use Spock for this example mostly for fun. I enjoy using Spock. In this example, I’ve setup Spock to use the same Spring context used by the Spring Boot Application. The Spring Boot Application class is actually a Spring Configuration class you can source into your Spring Integration tests.

Spock Spring Integration Test

In this Spock Integration test, using the Spring Boot configuration, I autowire in an instance of the JMS connection factory and setup a JMS producer to send a text message. This will drop a text message on the the same ActiveMQ JMS queue we configured Spring Integration to listen on.

SayHellowServiceJMSIT.groovy

Running the Spock Integration Test

Using IntelliJ, running the Spock integration test can simply be done by right clicking on the test method, and then clicking on ‘run’.

running a spock test in Intellij

 

Test Output

Spring Integration JMS Configuration for Spring Boot

Intentionally left an error in the Spring Integration configuration to demonstrate this error. The Spring Integration configuration be default is looking for a Spring Bean called ‘connectionFactory’. Spring Boot by default, creates the JMS connection factory using the name ‘jmsConnectionFactory’.

The solution is easy enough to implement. We just need to update the Spring Integration channel adapter to use the Spring Bean ‘jmsConnectionFactory’ instead of it’s default value of ‘connectionFactory.

si-config.xml

Running the Updated Configuration

When we run the Spock Integration Test again, we can see our expected hello world message in the console output.

Test Output

Conclusion

In this Spring Framework example, I’ve shown you how easy it is to use Spring Boot to configure an Active MQ broker for use with Spring Integration. This blog post was inspired by a real world example where I was coding a enterprise service using the Spring Framework. I needed to use Spring Integration to consume messages off of a MQSeries JMS queue. MQSeries is great, but its not very light weight, nor is it appropriate for Integration tests. Thus, I wrote my integration tests to use an embedded ActiveMQ broker. You can see how easy it was to use Spring Boot to provide the ActiveMQ broker, and dependency injection to wire everything up.

4
Share
,

This past week I had a real world use case for using Spring Integration Futures. I was looking into optimizing the checkout experience for a large ecommerce website. Consider what happens in a large scale website when an order is submitted. Typically, you will see a process something like:

  • Validate the place order form information
  • Verify the address against an address service
  • Verify the credit card with a payment processor
  • Verify available inventory

Each of these in a large scale enterprise are services. For example, it is common for an enterprise to subscribe to an address validation service. This helps ensure shipping accuracy. Or you’ll have a inventory service to help manage inventory levels. Normally not a problem. But when you have a black friday shopping special and thousands of users shopping on the site, managing inventory can become tricky.

Each of these services will take some time to execute. If called in sequence, the website response time slows down and impacts the user experience in the checkout flow. However, in my example here, there is no reason these service calls couldn’t be called concurrently. By calling the services concurrently, the response time now is the longest service call, not the sum of all the service calls. If each service call takes a half second, calling the services sequentially would take 2 seconds of elapsed time. Calling them concurrently only takes a half second.

A couple weeks back I wrote a blog post on testing Spring Integration Gateways.  In this use case, Spring Integration is the perfect tool. Spring Integration has a very cool feature to support asynchronous calls. When using Spring Integration Messaging Gateways, if you wrap the return time in a Java Future, Spring Integration will automatically handle the request in a different thread using a thread pool. As an application developer, this makes writing a multithreaded application very easy to do. The Spring Framework and Spring Integration handle the complexity of managing the worker threads and the thread pool.

In this post, I’m going to walk you through the configuration of the Spring Integration gateways and Spring service beans used to make these four service calls supporting my ecommerce place order example.

Spring Integration Code Examples

Command Objects

In this example, I’m going to use a command object. In a web application, this would typically have values bound to it from a form post. However, in today’s omni-channel retail environment, the website is not the only client I need to worry about. This request could be coming from a native iOS mobile application, a native Android mobile application, an in-store kiosk, or maybe a stand alone customer service application.

By using a command object, I’m decoupling my processing from the front end client. I don’t care where the request originated. Maybe it was a form post. Maybe a web service, could be a JMS request. It doesn’t really matter where the request originated.

Place Order Command

Domain Objects

For this example, I’ve created a couple domain objects. These are just simple POJOs I’m using to illustrate the example. In a real application these objects would be much more robust. 

Order

OrderLine

Product

Spring Integration Gateways

For this example, I’ve defined four different Spring Integration Messaging Gateways. Technically, I could have used just one Spring Integration Messaging Gateway, but that would have been a violation of the Single Responsibility Principle. This approach does lead to more class files. But when I need to maintain this code, I know where to look. The programming logic is clear and organized.

OrderGateway

The Order Gateway interface defines two methods. The first placeOrder  is the start of our processing chain.  This is where we will submit the command object. The second method is used in our the processing of the place order command object.

Note: notice the usage of the Java Future  for the return time of the validateOrder method. This is what instructs Spring Integration to perform the method call asynchronously using a thread pool.

AddressGateway

InventoryGateway

PaymentGateway

Spring Services

Since this is a Spring project, we’ll create our services as Spring Beans, and naturally will we be using Dependency Injection and program to an interface.

OrderService

OrderServiceImpl

The implementation of our Order Service is one of the more complex classes in this tutorial. You can see we are having Spring autowire our four Spring Integration Messaging Gateways into the class. In the placeOrderMethod , you can see I call a method on each of the four Spring Integration Gateways. Each method returns a Java Future. After all four are submitted, I go back to get the value of the Future. In this case, I’m using the Spring Errors object. If all four validation steps come back without errors, in a real system I’d persist the order to the database and do any post processing. But this is just a little sample to show off the use of Spring Integration Futures. So in this case, I’m just returning the command object either way.

Spring Integration Configuration

I had to expand on the Spring Integration configuration from our previous example. You’ll see I’m using the Spring Integration Gateway tag to define the four Spring Integration Gateways we’re using. Then I defined the Spring Integration channels and the appropriate Spring Integration service activators. Nothing new here over the previous example. Just a little more routing to take care of.

Notice how I did not define a thread pool? By default, Spring Integration is providing a thread pool for our use. You can of course define your own or update the settings of the default thread pool if needed.

si-config.xml

Running the Spring Integration Code

I’ve setup a Spock test to run the Spring Integration code in this example. 

OrderGatewayTests

When you run this Spock test you will see the following output:

Each the services I’ve wired into this example do simple print line statements out to the console. Each starts their respective output with the Id number of the thread they are running in. You can see from the output how each service is running concurrently in different threads.

Conclusion

As a programmer, Spring Integration is a very powerful tool to have in your toolbelt. You can see from this example how I’ve created a multithreaded application with a minimal amount of coding. I simply wrapped the return type I wanted on the Spring Integration Messaging Gateways with a Java Future. Spring Integration and Spring managed the thread pool for me. I didn’t need to worry about managing threads. The Spring Framework allowed me to focus on delivering the business solution, and took care of the complex boiler plate code.

Get The Code

I’ve committed the source code for this post to github. It is a Maven project which you can download and build. If you wish to learn more about the Spring Framework, I have a free introduction to Spring tutorial. You can sign up for this tutorial in the section below.

Source Code

The source code for this post is available on github. You can download it here.

0
Share
,

Spring Integration is a very powerful module in the Spring Framework. It was originally inspired by pivotal book in computer science called Enterprise Integration Patterns written by Gregor Hohpe and Bobby Woolf. While the Gang of Four focused their work on software design patterns, Enterprise Integration Patterns is focused on how disparate systems communicate with each other. As the industry has moved to highly scalable systems adopting cloud computing paradigms, the principles set forth in Enterprise Integration Patterns are highly relevant to Java programming.

Similar to the GoF focus, Spring Core largely focused on development within a single application or JVM environment.  Spring Integration builds upon the core principles of Spring Core to extend the Spring programming model to a message driven programming model. Abstracted from the developer when making a method call is the implementation details. Does it really matter if the method you are calling is a simple method call, a web service, a JMS Message, or making a request to the database? No, it should not. And more importantly, the implementation details should not leak back into your code.

In this example, I’ll step through the use of a Spring Integration Message Gateway for a classic “Hello World” programming example. I’ll show you how to use a Spring Integration Messaging Gateway for a simple send message, a request / response example, and an async request response example.

Spring Integration Hello World Code Example

Hello World Service Bean

For our example, we’re going to use a very simple service bean to either say hello or get a hello message. In a real world example, this code could be a direct method call, behind a web service, or perhaps its a message driven bean off a AQMP queue.

Spring Integration Gateway

The next component we need to setup is an interface class, which we will use for the Spring Integration Gateways. When coding to use Spring Integration, messaging gateways are a very convenient programming option to use. They have a very minimal impact on your application code. As the developer, you only need to create the interface specification. Spring Integration will provide the actual implementation and inject it into your class at run time. There is one small bit of leakage into your application code with the @Gateway  annotation. I could have coded this example without the annotations, but I find them very convenient to use. This annotation directs Spring Integration which messaging channel to use for the method call of the interface.

Spring Integration Gateway Configuration

The messaging gateway needs to be defined in your Spring Integration configuration. Spring Integration will not create the gateway bean without this configuration line.

Spring Integration Channel

Spring Integration Channels are a core concept to Spring Integration. They are used to decouple message producers (our gateway) from message consumers (our hello world bean). This abstraction is important because the channel could be a direct method call, or a JMS queue. The important take away is the decoupling. Neither the message producer nor the message consumer is aware of details about the implementation of the messaging channel.

In XML configuration snippet below, I’ve defined two messaging channels. Spring Integration has a number of options for defining messaging channels. The default channel is a direct channel, which is perfect for our hello world example.

Spring Integration Service Activator

Spring Integration has a concept of Service Activators. This is basically a way to configure a message consumer on a channel. This is completely decoupled from the gateway. Its important to remember the service activator is associated with a channel, and not a gateway or a gateway method. When you’re new to Spring Integration, it can be easy to lose site of this important distinction.

In this XML configuration snippet, I’ve defined two service activators.

Spring Integration XML Configuration

The complete XML configuration used in our hello world example follows below. You’ll see that I’m using a component scan to create the Hello World Service bean in the Spring context.

Running the Spring Integration Hello World Example

I’ve setup two examples to run our Spring Integration Hello World example. One using Spring Boot, and the second using JUnit. 

Spring Boot Application

In this example, I’m using Spring Boot to bring up the Spring Context. Since I placed the Spring Integration configuration in a XML configuration file, I need to use the @ImportResource  annotation to tell Spring Boot to import the XML configuration file.  In the code, I ask the Spring Context for an instance of the gateway bean. Then I call our three methods. The first is a simple send message with no return value. Our messaging service bean will write the hello message to the console. In the second example, I’m getting a message back from the Hello World Service bean.  The final example is a little more interesting. In this case, I’ve setup an asynchronous call. By specifying a Future in the return type, Spring Integration will automatically make a asynchronous call. This is an ideal technique to use when you have a longer running call (such as a remote web service), and you can do other work while the call is being made.

When you execute the above code, you will receive the following output in the console.

JUnit Example

We can run the same code as a JUnit test as well. In this case, I’m allowing Spring to autowire the Spring Integration gateway into my test. Then I have three separate tests to execute our three different hello world examples.

This is more typical of how you would use a Spring Integration gateway in your application code. You can utilize dependency injection in Spring to inject an instance of the Spring Integration gateway instance into your class at run time.

When you run the JUnit tests in this class, you will get the following output in the console.

Conclusion

This has been a very simple Hello World example using Spring Integration. While this post only scratches the surface of the abilities of Spring Integration, I hope you can see how easy it is to utilize Spring Integration in your code. As you learn to develop large scale enterprise applications, you will find that Spring Integration is an important module in the Spring Framework.

Get The Code

I’ve committed the source code for this post to github. It is a Maven project which you can download and build. If you wish to learn more about the Spring Framework, I am a free introduction to Spring tutorial. You can sign up for this tutorial in the section below.

Source Code

The source code for this post is available on github. You can download it here.

0
Share