Sunday, 16 May 2021

Spring integration: Message component

In Java terms, Message is a generic wrapper on any object with metadata. Message component comprises of headers and payload.

 

What kind of payload a message holds?

A message holds any type of data like string, integer, json document, xml, image, binary data, any java object etc.,

 


Why headers?

Headers are used to provide additional information about the data. Header hold the information like message id, timestamp, correlationId, and return address etc.,

 

For example, if you want to attach a file via an email using spring integration.

a.   Payload holds the file content

b.   Following custom headers hold metainformation used to deliver a

Header

Description

fileName

Name of the file

from

From mail address

to

To mail addresses

cc

Cc mail addresses

bcc

Bcc mail addresses

subject

Mail subject

Body

Mail body

 

Spring integration define a generic Message interface to represent a message object.

public interface Message<T> {

	/**
	 * Return the message payload.
	 */
	T getPayload();

	/**
	 * Return message headers for the message (never {@code null} but may be empty).
	 */
	MessageHeaders getHeaders();

}


'GenericMessage' class implements Message interface. You can write custom message by implementing Message interface.

 

Message is immutable

Once a message is created, it is immutable.

 

GenericMessage class provides following constructors to define a message instance.

 

public GenericMessage(T payload)

public GenericMessage(T payload, Map<String, Object> headers)

public GenericMessage(T payload, MessageHeaders headers)

payload: Specifies the message payload, it must not be null.

headers: Message headers.

 

Example

Message<String> message = new GenericMessage<>(payload, headers);

 

Find the below working application.

 

Step 1: Create new maven project ‘generic-message-demo’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>generic-message-demo</artifactId>
	<version>1</version>

	<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.0</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-integration</artifactId>
		</dependency>

	</dependencies>

</project>


Step 3: Create new package 'com.sample.app.endpoints' and define CustomGateway and PrintService classes.

 

CustomGateway.java

package com.sample.app.endpoints;

import org.springframework.integration.annotation.Gateway;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.messaging.Message;

@MessagingGateway(name = "myGateway", defaultRequestChannel = "inputChannel")
public interface CustomGateway {

	@Gateway(requestChannel = "echoChannel", replyTimeout = 2, requestTimeout = 200)
	public void print(Message<String> message);


}


PrintService.java

package com.sample.app.endpoints;

import java.util.Map;
import java.util.Set;

import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;

@Component
public class PrintService {

	@ServiceActivator(inputChannel = "echoChannel")
	public void print(Message<String> message) {
		String payload = message.getPayload();
		MessageHeaders messageHeaders = message.getHeaders();

		System.out.println("Headers");
		Set<Map.Entry<String, Object>> messageHeadersSet = messageHeaders.entrySet();

		for (Map.Entry<String, Object> headerEntry : messageHeadersSet) {
			System.out.println(headerEntry.getKey() + " -> " + headerEntry.getValue());
		}

		System.out.println("\nPayload");
		System.out.println(payload);
	}

}


Step 4: Define App class.

 

App.java

package com.sample.app;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.GenericMessage;

import com.sample.app.endpoints.CustomGateway;

@SpringBootApplication
@Configuration
public class App {

	@Autowired
	private CustomGateway gateway;

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

	@Bean
	public CommandLineRunner demo() {
		return (args) -> {
			String json = "{\"name\" : \"Krishna\"}";

			Map<String, Object> headers = new HashMap<>();
			headers.put("my-content-type", "application/json");
			headers.put("my-origin", "localhost");
			headers.put("my-content-encoding", "utf-8");

			Message<String> message = new GenericMessage<>(json, headers);

			gateway.print(message);
		};
	}

}


Total project structure looks like below.




Run App.java, you will see below messages in console.

Headers
replyChannel -> nullChannel
my-content-type -> application/json
my-content-encoding -> utf-8
id -> ce2df15b-27eb-5a45-c1e3-3a9c8d1e46ce
my-origin -> localhost
timestamp -> 1617349660418

Payload
{"name" : "Krishna"}

 

As you see the Headers sections, apart from the custom headers (my-content-type, my-content-encoding, my-origin) there are some default headers like id, timestamp and replyChannel added by spring integration framework.

 

You can download complete working application from below link.

https://github.com/harikrishna553/springboot/tree/master/spring-integration/generic-message-demo

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment