Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Throttling in Spring Integration

DZone's Guide to

Throttling in Spring Integration

Follow along with this tutorial to learn how to set up throttling in your system using a few different open source frameworks along with Java and XML code.

· Integration Zone ·
Free Resource

The State of API Integration 2018: Get Cloud Elements’ report for the most comprehensive breakdown of the API integration industry’s past, present, and future.

Writing Throttlers in Spring Integration is very simple. In my current project, I was asked to send 15 SOAP requests per second to a downline system and not to send more than that; and to make sure that it was parallel. For more information or to understand Spring Integration, follow this link to the docs. In the below diagram, the left side Producer threads are publishing messages to the Spring Integration Executor channel type, and this Executor channel bridges to another channel called "Bridge Channel," which is a queue Channel type and keeps messages from the Executor Channel. The queue channel has Poller and it pulls a maximum of 15 messages per second. On the other side of the Service Activator, the endpoint receives 15 messages per second and adds additional information to messages before publishing them to another Executor channel (where this Executor Channel has subscribed Service Activator as a worker thread). I have written some sample code using Spring Integration JUnit with XML configuration. Image title

1.  Define the input channel  - Spring Integration Executor Channel. 

<int:channel id="inputChannel">
   <int:dispatcher task-executor="producerThreadExecutor"/>
</int:channel>

<task:executor id="producerThreadExecutor" pool-size="50" queue-capacity="10"  rejection-policy="DISCARD" />

2. Spring JUnit test. This class publishes a message to the inputChannel using Java multi-threads.

package com.uppi.poc.throttler;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.channel.ExecutorChannel;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application-test.xml")
public class SpringThrottlerTest {

 @Autowired
 private ExecutorChannel inputChannel;
 private AtomicInteger value = new AtomicInteger(1);

 @Test
 public void showMe() throws Exception {
  ThreadPoolExecutor be = new ThreadPoolExecutor(100, 200, 1000, TimeUnit.MILLISECONDS,
   new LinkedBlockingQueue < Runnable > ());
  for (int i = 1; i <= 90; i++) {
   be.submit(new TaskSubmiter(inputChannel, value));
  }
  TimeUnit.SECONDS.sleep(28);
 }

 private static class TaskSubmiter implements Runnable {
  private final ExecutorChannel inputChannel;
  private final AtomicInteger i;

  public TaskSubmiter(final ExecutorChannel testChannel, final AtomicInteger i) {
   this.inputChannel = testChannel;
   this.i = i;
  }

  @Override
  public void run() {
   inputChannel.send(
    MessageBuilder.withPayload(Thread.currentThread().getName() + ",= " + i.getAndIncrement()).build());
  }

 }
}

3. Define QueueChannel with a capacity of 100.

<int:channel id="throttlerChannel">
       <int:queue capacity="100"/> <!-- for example queue size, you can increase this capacity based on your requirement -->
 </int:channel>

4. This step can be optional. If you don't have any additional information to add to the message, just use another bridge with a poller. See below: 

<int:bridge input-channel="inputChannel" output-channel="throttlerChannel" />

<int:service-activator  ref="producer" method="process" input-channel="throttlerChannel">
   <int:poller fixed-delay="1000" max-messages-per-poll="15"></int:poller> <!-- per second 15 messages -->
</int:service-activator>

<bean id="producer" class="com.uppi.poc.throttler.MessageChunkProducer" />

OR

Bridge from the Queue Channel to the Executor Channel (use this bridge only if you don't have any dependencies or additional information to add to the message).

<int:bridge input-channel="throttlerChannel" output-channel="receiverChannel" >
     <int:poller fixed-delay="1000" max-messages-per-poll="15"></int:poller>
</int:bridge>

<!-- comment the following code -->
<!--  <int:service-activator  ref="producer" method="process" input-channel="throttlerChannel">
        <int:poller fixed-delay="1000" max-messages-per-poll="3"></int:poller>
</int:service-activator>
 <bean id="producer" class="com.uppi.poc.throttler.MessageChunkProducer" /> -->

5. Publishing a message to the Executor channel where a worker thread consumes it (optional, see step 4).

package com.uppi.poc.throttler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.channel.ExecutorChannel;
import org.springframework.integration.support.MessageBuilder;

public class MessageChunkProducer {

 @Autowired
 private ExecutorChannel receiverChannel;
 public void process(String msg) {
  receiverChannel.send(MessageBuilder.withPayload(msg).build());
 }
}

6.  Define the Receiver Executor Channel, where the worker thread can consume it.

<int:channel id="receiverChannel">
       <int:dispatcher task-executor="workerThreadExecutor"/>
</int:channel>
<task:executor id="workerThreadExecutor" pool-size="15" queue-capacity="10"  rejection-policy="DISCARD" />

<int:service-activator id="worker" ref="workerThread" method="process" input-channel="receiverChannel" />
<bean id="workerThread" class="com.uppi.poc.throttler.WorkerThread" /> 

7. Define the Service Activator endpoint (worker thread).

package com.uppi.poc.throttler;

import java.util.Date;
import java.util.logging.Logger;

public class WorkerThread {
 private static final Logger LOG = Logger.getLogger(WorkerThread.class.getName());
 public void process(String msg) {
  LOG.info("Date " + new Date() + ",Thread " + Thread.currentThread().getName() + ", Msg= " + msg);
 }
}

The complete code for this article can be accessed on GitHub.

Sample Output:

Image title

Your API is not enough. Learn why (and how) leading SaaS providers are turning their products into platforms with API integration in the ebook, Build Platforms, Not Products from Cloud Elements.

Topics:
spring integration ,integration ,junit

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}