How to check before sending a message to the server with Spring Integration

Introduction

I see quite a few articles about Spring Framework, but I can't find any articles about Spring Integration, probably because they are not major in Japan, so I would like to post them irregularly. (I'm not saying I'll post: sunglasses :)

Development environment

Where is the process of sending a message via TCP communication in the first place?

The handleRequestMessage of the TcpOutboundGateway. In this method, we are sending a message to the server using TcpConnection obtained from ClientConnectionFactory.

TcpOutboundGateway message transmitter (partially omitted)

TcpOutboundGateway.java


protected Object handleRequestMessage(Message<?> requestMessage) {
	TcpConnection connection = null;
	String connectionId = null;
	try {
			connection = this.connectionFactory.getConnection();
			AsyncReply reply = new AsyncReply(this.remoteTimeoutExpression.getValue(this.evaluationContext,
					requestMessage, Long.class));
			connectionId = connection.getConnectionId();
			this.pendingReplies.put(connectionId, reply);
			if (logger.isDebugEnabled()) {
				logger.debug("Added pending reply " + connectionId);
			}
			connection.send(requestMessage);

Reason for sending check

Normally, it is not necessary to check when sending, but depending on the case, there may be a requirement such as "monitor the status of a component and do not send a message depending on that status." That's the deal I'm working on right now: v:

How to check transmission

For the time being, there are two methods I have come up with.

Extend TcpOutbound Gateway

Well, it's a straightforward idea ... Extend TcpOutboundGateway to override handleRequestMessage. Send processing is performed only when the return value of getStatus is true.

CustomizedTcpOutboundGateway.java


public class CustomizedTcpOutboundGateway extends TcpOutboundGateway {

  @Override
  public Object handleRequestMessage(Message<?> message) {
    if (getStatus()) {
      return super.handleRequestMessage(message);
    } else {
      return new GenericMessage<String>("can not send");
    }
  }

The return value of the original handleRequestMessage is of type ʻObject, but in the case of a normal system, the received message is returned, so an appropriate Message` object is returned. This depends on your requirements.

Take advantage of Interceptor

The method of ↑ is fine, but if you don't want to extend the framework class too much, there is a way to utilize ʻInterceptor`. The procedure is as follows.

First, extend TcpConnectionInterceptor and insert a check process when sending a message.

TcpConnectionInterceptor.java


public class TcpConnectionInterceptor extends TcpConnectionInterceptorSupport {

  @Override
  public void send(Message<?> message) throws Exception {
    if (getStatus()) {
      super.send(message);
    }
  }
 //Abbreviation

Send a message with the value of getStatus (). Since TcpConnectionInterceptorSupport has multiple methods around the connection, it is possible to insert processing at timings other than before sending like this time: hugging :.

Next, create a class that implements the TcpConnectionInterceptorFactory that returns the TcpConnectionInterceptor that you just created. The implementation is appropriate.

CustomizedTcpConnectionInterceptorFactory.java


public class CustomizedTcpConnectionInterceptorFactory implements TcpConnectionInterceptorFactory {

  private final TcpConnectionInterceptorSupport interceptor;

  public CustomizedTcpConnectionInterceptorFactory(TcpConnectionInterceptorSupport interceptor) {
    this.interceptor = interceptor;
  }

  @Override
  public TcpConnectionInterceptorSupport getInterceptor() {
    return interceptor;
  }
}

After that, pass this to TcpConnectionInterceptorFactoryChain and set it to ClientConnectionFactory.

  <int-ip:tcp-connection-factory type="client" host="localhost" port="56789"
    deserializer="deserializer" serializer="serializer" interceptor-factory-chain="interceptorFactoryChain" />

  <bean id="interceptorFactoryChain"
    class="org.springframework.integration.ip.tcp.connection.TcpConnectionInterceptorFactoryChain">
    <property name="interceptors">
      <array>
        <bean
          class="com.neriudon.sample.interceptor.CustomizedTcpConnectionInterceptorFactory"
          c:interceptor-ref="tcpConnectionInterceptor" />
      </array>
    </property>
  </bean>

  <bean id="tcpConnectionInterceptor"
    class="com.neriudon.sample.interceptor.TcpConnectionInterceptor" />

The ClientConnectionFactory settings are appropriate. : frowning2:

This method is a little complicated, but is it an advantage that you don't mess with the original Gateway?

How did you come to post this article?

As a memo because this function was needed for the project I am currently involved in.

at the end

Even if you google with the class name of Spring Integration, there are many cases where Japanese sites do not hit, so please try Spring Integration as well. : kissing_heart:

Recommended Posts

How to check before sending a message to the server with Spring Integration
How to interact with a server that does not crash the app
How to access Socket directly with the TCP function of Spring Integration
How to create a server executable JAR and WAR with Spring gradle
How to take a screenshot with the Android Studio emulator
Check how to set the timeout when connecting with Spring + HikariCP + MySQL and executing SQL
I tried to check the operation of gRPC server with grpcurl
How to check for the contents of a java fixed-length string
How to split Spring Boot message file
How to apply thymeleaf changes to the browser immediately with #Spring Boot + maven
I examined the flow of TCP communication with Spring Integration (server edition)
Send a request to the backend after authenticating with Spring Cloud Gateway
How to check the logs in the Docker container
How to use MyBatis2 (iBatis) with Spring Boot 1.4 (Spring 4)
How to get the ID of a user authenticated with Firebase in Swift
How to use built-in h2db with spring boot
How to check the latest version of io.spring.platform to describe in pom.xml of Spring (STS)
How to deploy a system created with Java (Wicket-Spring boot) to an on-campus server
[Swift] How to link the app with Firebase
How to add a classpath in Spring Boot
How to create an Excel form using a template file with Spring MVC
Create a web api server with spring boot
[Spring Boot] How to refer to the property file
How to check Rails commands in the terminal
How to build a Jenkins server with a Docker container on CentOS 7 of VirtualBox and access the Jenkins server from a local PC
How to save a file with the specified extension under the directory specified in Java to the list
[Docker] How to see the contents of Volumes. Start a container with root privileges.
How to delete child elements associated with a parent element at the same time
How to change the action with multiple submit buttons
How to make a factory with a model with polymorphic association
How to run the SpringBoot app as a service
How to apply HandlerInterceptor to http inbound-gateway of Spring Integration
How to write a unit test for Spring Boot 2
[Java] How to omit spring constructor injection with Lombok
[Spring] Read a message from a YAML file with MessageSource
How to delete a new_record object built with Rails
How to create a Spring Boot project in IntelliJ
[Spring Boot] How to create a project (for beginners)
How to manually generate a JWT with Rails Knock
Organized how to interact with the JDK in stages
[How to insert a video in haml with Rails]
HTTPS connection with Java to the self-signed certificate server
How to boot by environment with Spring Boot of Maven
How to make a mod for Slay the Spire
How to get started with creating a Rails app
[Docker + Rails] How to deal with Rails server startup failure
[Java] How to start a new line with StringBuilder
How to use the same Mapper class in multiple data sources with Spring Boot + MyBatis
Display a balloon message in BarButtonItem of NavigationBar with a size according to the amount of text.
How to reduce the load on the program even a little when combining characters with JAVA
[Rails] What to do when the view collapses when a message is displayed with the errors method
How to correctly check the local HTML file in the browser
How to request a CSV file as JSON with jMeter
SDWebImage: How to clear the cache for a particular UIImageView
How to divide a two-dimensional array into four with ruby
How to use a foreign key with FactoryBot ~ Another solution
How to create a form to select a date from the calendar
The first WEB application with Spring Boot-Making a Pomodoro timer-
A story packed with the basics of Spring Boot (solved)
How to create a placeholder part to use in the IN clause
Check the operation of two roles with a chat application