DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Spring Boot Microservices + Apache Camel: A Hello World Example
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • How Kafka Can Make Microservice Planet a Better Place
  • How to Setup the Spring Cloud Config Server With Git

Trending

  • Securing Your Applications With Spring Security
  • Extracting Maximum Value From Logs
  • Build Quicker With Zipper: Building a Ping Pong Ranking App Using TypeScript Functions
  • The API-Centric Revolution: Decoding Data Integration in the Age of Microservices and Cloud Computing
  1. DZone
  2. Coding
  3. Java
  4. Integrating with Rabbit MQ Using Spring Integration Java DSL

Integrating with Rabbit MQ Using Spring Integration Java DSL

Here's how to integrate RabbitMQ messaging using Spring Integration's Java language DSL for connecting complex enterprise systems.

Biju Kunjummen user avatar by
Biju Kunjummen
·
Aug. 25, 16 · Tutorial
Like (2)
Save
Tweet
Share
16.34K Views

Join the DZone community and get the full member experience.

Join For Free

I recently attended the Spring One conference 2016 in Las Vegas and had the good fortune to see from near and far some of the people that I have admired for a long time in the software world. I personally met two of them, who have actually merged some of my Spring Integration related minor contributions from a few years ago — Gary Russel and Artem Bilan and they inspired me to look again at Spring Integration which I have not used for a while. 

I was once more reminded of how Spring Integration makes any complex Enterprise integration scenario look easy. I am happy to see that Spring Integration Java based DSL is now fully integrated into the Spring Integration umbrella and higher level abstractions like Spring Cloud Stream (introductions thanks to my good friend and a contributor to this project Soby Chacko), which makes some of the message-driven scenarios even easier.

In this post, I am just revisiting a very simple integration scenario with RabbitMQ and in a later post will re-implement it using Spring Cloud Stream.

Consider a scenario where two services are talking to each other via a RabbitMQ broker in between, one of them generating some kind of a work, the other processing this work. 


Producer

The Work unit producing/dispatching part can be expressed in code using Spring Integration Java DSL the following way:?


@Configuration public class WorksOutbound {       
  @Autowired     
  private RabbitConfig rabbitConfig;       
  @Bean     public IntegrationFlow toOutboundQueueFlow() {         
    return IntegrationFlows.from("worksChannel")                 
      .transform(Transformers.toJson())                 
      .handle(Amqp.outboundAdapter(rabbitConfig.worksRabbitTemplate()))   
      .get();     } 
}


This is eminently readable — the flow starts by reading a message off a channel called "worksChannel", transforms the message into a JSON and dispatches it off using an Outbound channel adapter to a RabbitMQ exchange. Now, how does the message get to the channel called "worksChannel"? I have configured it via a Messaging gateway, an entry point to the Spring Integration world: ?

@MessagingGateway public interface WorkUnitGateway 
{  
  @Gateway(requestChannel = "worksChannel")  
 void generate(WorkUnit workUnit);   
}


So now if a Java client wanted to dispatch a "work unit" to RabbitMQ, the call would look like this:?

WorkUnit sampleWorkUnit = new WorkUnit(UUID.randomUUID().toString(), definition); 
workUnitGateway.generate(sampleWorkUnit);


I have brushed over a few things here —specifically the Rabbit MQ configuration, which is run of the mill however and is available here.

Consumer

Along the lines of a producer, a consumer's flow would start by receiving a message from RabbitMQ queue, transforming it to a domain model and then processing the message, expressed using Spring Integration Java DSL the following way:

@Configuration
public class WorkInbound {
 
    @Autowired
    private RabbitConfig rabbitConfig;
 
    @Autowired
    private ConnectionFactory connectionFactory;
 
    @Bean
    public IntegrationFlow inboundFlow() {
        return IntegrationFlows.from(
                Amqp.inboundAdapter(connectionFactory, rabbitConfig.worksQueue()).concurrentConsumers(3))
                .transform(Transformers.fromJson(WorkUnit.class))
                .handle("workHandler", "process")
                .get();
    }
}


The code should be intuitive, the workHandler above is a simple Java pojo and looks like this, doing the very important job of just logging the payload:?

@Service public class WorkHandler {     
  private static final Logger LOGGER = LoggerFactory.getLogger(WorkHandler.class);
  public void process(WorkUnit workUnit) {         
    LOGGER.info("Handling work unit - id: {}, definition: {}", 
                workUnit.getId(), 
workUnit.getDefinition());                    } 
}


That is essentially it. Spring Integration provides an awesome facade to what would have been a fairly complicated code had it been attempted using straight Java and raw RabbitMQ libraries. Spring Cloud Stream makes this entire set-up even simpler and would be the topic of a future post.

I have posted this entire code at my GitHub repo if you are interested in taking this for a spin.

Spring Integration Domain-Specific Language Spring Framework Enterprise integration Java (programming language) Spring Cloud

Published at DZone with permission of Biju Kunjummen, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot Microservices + Apache Camel: A Hello World Example
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • How Kafka Can Make Microservice Planet a Better Place
  • How to Setup the Spring Cloud Config Server With Git

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: