Making queries on demand: MongoDB outbound gateway

1 Introduction

In order to read data from MongoDb, Spring Integration comes with the MongoDb inbound channel adapter. This adapter uses a poller to continuously retrieve documents from the database. However, sometimes we may need to query the database on demand, based on the result of another endpoint.

Taking advantage of Spring’s extensibility, I implemented a MongoDb outbound gateway. The purpose of this gateway is to react to some request, make a query to the database and return the result.

In order to show you how the gateway works, I will use a simple example and modify it to implement the gateway with different configurations.

This example consists in a messaging gateway as the entry point to the integration flow. Once a message enters the flow, the mongoDb outbound gateway makes a query to the database and the result is then sent to another channel where a service activator will process it.

The source code for these examples and the gateway implementation can be found in my repository.

2 Java DSL example

I implemented the MongoDb static class to ease the definition of the gateway. I took the idea from the Spring Integration Jpa class.

In the following configuration you can see the flow requestPerson. An invocation to PersonService’s send method will send a message to the flow, where the mongoDb outbound gateway will then query the database with a pre-defined query ({id : 1}):

@ComponentScan("xpadro.spring.integration.mongodb")
@IntegrationComponentScan("xpadro.spring.integration.mongodb")
public class JavaDSLQueryConfiguration {
    
    @MessagingGateway
    public interface PersonService {
        
        @Gateway(requestChannel = "requestPerson.input")
        void send(RequestMessage requestMessage);
    }

    @Bean
    @Autowired
    public IntegrationFlow requestPerson(MongoDbFactory mongo) {
        return f -> f
                .handle(outboundGateway(mongo))
                .handle(resultHandler(), "handle");
    }

    @Bean
    public ResultHandler resultHandler() {
        return new ResultHandler();
    }

    private MongoDbOutboundGatewaySpec outboundGateway(MongoDbFactory mongo) {
        return MongoDb.outboundGateway(mongo)
                .query("{id: 1}")
                .collectionNameExpression(new LiteralExpression("person"))
                .expectSingleResult(true)
                .entityClass(Person.class);
    }
}

 

The result handler is a “very useful” component which will log the retrieved person:

public class ResultHandler {

    public void handle(Person person) {
        System.out.println(String.format("Person retrieved: %s", person));
    }
}

 

In order to start the flow, the following application sends a message to the PersonService gateway:

@SpringBootApplication
@EnableIntegration
@Import(JavaDSLQueryConfiguration.class)
public class JavaDSLQueryApplication extends AbstractApplication {

	public static void main(String[] args) {
		ConfigurableApplicationContext context = SpringApplication.run(JavaDSLQueryApplication.class, args);
		new JavaDSLQueryApplication().start(context);
	}

	public void start(ConfigurableApplicationContext context) {
		resetDatabase(context);

		JavaDSLQueryConfiguration.PersonService personService = context.getBean(JavaDSLQueryConfiguration.PersonService.class);
		personService.send(new RequestMessage());
	}
}

 

As a note, the abstract class just contains the logic to set up the database, which is used along all the other examples.

3 Java DSL example with dynamic query expression

The previous example was useful to see how to define the gateway, but having a hardcoded query may not be the most used case.

In this example, the query is defined in the message sent to the integration flow:

personService.send(new RequestMessage("{id : 2}"));

 

In the configuration file, the gateway’s queryExpression property resolves the query dynamically by retrieving the data property of the message’s payload:

private MongoDbOutboundGatewaySpec outboundGateway(MongoDbFactory mongo) {
        return MongoDb.outboundGateway(mongo)
                .queryExpression("payload.data")
                .collectionNameExpression(new LiteralExpression("person"))
                .expectSingleResult(true)
                .entityClass(Person.class);
    }

 

4 Java DSL example returning multiple results

The two previous examples retrieved a single document from the database. In this next example, the query returns a list with all documents matching the query:

In the request message we specify the query to find all documents in the persons collection:

personService.send(new RequestMessage("{}"));

 

In the configuration, we have to remove the expectSingleResult property from the gateway (or set it to false). Additionally, we can specify a limit:

private MongoDbOutboundGatewaySpec outboundGateway(MongoDbFactory mongo) {
        return MongoDb.outboundGateway(mongo)
                .queryExpression("payload.data")
                .collectionNameExpression(new LiteralExpression("person"))
                .entityClass(Person.class)
                .maxResults(2);
    }

 

Finally, we have to define another method in the ResultHandler class to handle multiple results:

public void handle(List<Person> persons) {
        String names = persons.stream().map(Person::getName).collect(Collectors.joining(", "));
        System.out.println(String.format("Persons retrieved: %s", names));
    }

 

5 Java Config example

In this last example, Java Config is used instead of Java DSL to configure the whole flow. On the application’s side everything is the same. We just query the person service for a specific document:

personService.send(new RequestMessage("{id : 3}"));

 

When using Java Config, we have to build the MongoDbExecutor, which is used by the gateway to do the queries.

@ComponentScan("xpadro.spring.integration.mongodb")
@IntegrationComponentScan("xpadro.spring.integration.mongodb")
public class JavaConfigQueryConfiguration {

    @MessagingGateway
    public interface PersonService {

        @Gateway(requestChannel = "personInput")
        void send(RequestMessage requestMessage);
    }

    @Bean
    public ResultServiceActivator resultHandler() {
        return new ResultServiceActivator();
    }

    @Bean
    @ServiceActivator(inputChannel = "personInput")
    public MessageHandler mongodbOutbound(MongoDbFactory mongo) {
        MongoDbExecutor mongoDbExecutor = new MongoDbExecutor(mongo);
        mongoDbExecutor.setCollectionNameExpression(new LiteralExpression("person"));
        mongoDbExecutor.setMongoDbQueryExpression("payload.data");
        mongoDbExecutor.setExpectSingleResult(true);
        mongoDbExecutor.setEntityClass(Person.class);

        MongoDbOutboundGateway gateway = new MongoDbOutboundGateway(mongoDbExecutor);
        gateway.setOutputChannelName("personOutput");

        return gateway;
    }
}

 

Listening to the gateway’s output channel, we define a service activator to handle the retrieved person:

public class ResultServiceActivator {

    @ServiceActivator(inputChannel = "personOutput")
    public void handle(Person person) {
        System.out.println(String.format("Person retrieved: %s", person));
    }
}

 

6 Conclusion

An outbound gateway is suitable when you need to do queries on demand instead of actively polling the database. Currently, this implementation supports setup with Java Config and Java DSL. For now, I haven’t implemented the parsers needed to support XML configuration since I think these two ways of configuration cover the main necessity.

If you found this post useful, please share it or star my repository 🙂

I’m publishing my new posts on Google plus and Twitter. Follow me if you want to be updated with new content.

 

2 thoughts on “Making queries on demand: MongoDB outbound gateway

  1. Hello ,

    I saw your tweets and thought I will check your website. Have to say it looks very good!
    I’m also interested in this topic and have recently started my journey as young entrepreneur.

    I’m also looking for the ways on how to promote my website. I have tried AdSense and Facebok Ads, however it is getting very expensive.
    Can you recommend something what works best for you?

    Would appreciate, if you can have a quick look at my website and give me an advice what I should improve: http://janzac.com/
    (Recently I have added a new page about FutureNet and the way how users can make money on this social networking portal.)

    I have subscribed to your newsletter. 🙂

    Hope to hear from you soon.

    P.S.
    Maybe I will add link to your website on my website and you will add link to my website on your website? It will improve SEO of our websites, right? What do you think?

    Regards
    Jan Zac

    1. Hello Jan,

      I wish you luck on your new journey! 🙂

      Unfortunately, I cannot recommend you which is the best way to monetise your blog since I am currently not doing it.

Leave a Reply

Your email address will not be published. Required fields are marked *