{{announcement.body}}
{{announcement.title}}

Intro to Spring Data MongoDB Reactive and How to Move It to the Cloud

DZone 's Guide to

Intro to Spring Data MongoDB Reactive and How to Move It to the Cloud

In this article, see an introduction to Spring Data MongoDB Reactive and see how to move it to the cloud.

· Java Zone ·
Free Resource

In this post, we're going to see how to configure and implement database operations using Reactive Programming through Spring Data Reactive Repositories with MongoDB to run locally and then see how to move it smoothly to the cloud thought Platform.sh. 

Reactive programming is a programming paradigm that promotes an asynchronous, non-blocking, event-driven approach to data processing. Reactive programming involves modeling data and events as observable data streams and implementing data processing routines to react to the changes in those streams.

To illustrate Reactive MongoDB, we'll create an application to handle and store the goods of Greek mythology. In order to use Reactive MongoDB, we need to add the dependency to our pom.xml.

XML
 




x
54


 
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4
   <modelVersion>4.0.0</modelVersion>
5
 
          
6
   <groupId>sh.platform.example</groupId>
7
   <artifactId>template-spring-mongodb-reactive</artifactId>
8
   <version>0.0.1</version>
9
 
          
10
   <properties>
11
    <platform.sh.version>2.2.3</platform.sh.version>
12
    <java.version>1.8</java.version>
13
</properties>
14
 
          
15
<parent>
16
    <groupId>org.springframework.boot</groupId>
17
    <artifactId>spring-boot-starter-parent</artifactId>
18
    <version>2.2.6.RELEASE</version>
19
</parent>
20
 
          
21
<dependencies>
22
    <dependency>
23
        <groupId>org.springframework.boot</groupId>
24
        <artifactId>spring-boot-starter-webflux</artifactId>
25
    </dependency>
26
    <dependency>
27
        <groupId>org.springframework.boot</groupId>
28
        <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
29
    </dependency>
30
    <dependency>
31
        <groupId>org.springframework.boot</groupId>
32
        <artifactId>spring-boot-starter-test</artifactId>
33
        <scope>test</scope>
34
    </dependency>
35
</dependencies>
36
 
          
37
<build>
38
    <finalName>spring-reactive</finalName>
39
    <plugins>
40
        <plugin>
41
            <groupId>org.springframework.boot</groupId>
42
            <artifactId>spring-boot-maven-plugin</artifactId>
43
        </plugin>
44
    </plugins>
45
</build>
46
 
          
47
<repositories>
48
    <repository>
49
        <id>oss.sonatype.org-snapshot</id>
50
        <url>http://oss.sonatype.org/content/repositories/snapshots</url>
51
    </repository>
52
</repositories>
53
</project>
54
 
          



The next step is to configure the infrastructure connection, we need to use the  @EnableReactiveMongoRepositories  alongside with some infrastructure setup:

Java
 




x


 
1
import org.springframework.context.annotation.Configuration;
2
import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories;
3
 
          
4
@Configuration
5
@EnableReactiveMongoRepositories
6
public class MongoConfig{
7
 
          
8
}



We'll create a God entity and then annotated it with @Document to use it in the database operations.

Java
 




x


 
1
 
          
2
import org.springframework.data.annotation.Id;
3
import org.springframework.data.mongodb.core.mapping.Document;
4
 
          
5
import java.util.Objects;
6
import java.util.Set;
7
 
          
8
@Document
9
public class God {
10
 
          
11
    @Id
12
    private String name;
13
 
          
14
    private Integer age;
15
 
          
16
    private Set<String> powers;
17
 
          
18
    //getter and setter
19
}
20
 
          



The next step is to create a Repository interface. The goal of the Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores. Now with the Reactive model, we get the same set of methods and specifications, except that we'll deal with the results and parameters in a reactive way.

Java
 







Besides the repositories approach, there is the ReactiveMongoTemplate where we won't cover it.

The last step is the controller; what changed is the return in the methods.

Java
 




x


 
1
import org.springframework.beans.factory.annotation.Autowired;
2
import org.springframework.http.HttpStatus;
3
import org.springframework.web.bind.annotation.DeleteMapping;
4
import org.springframework.web.bind.annotation.GetMapping;
5
import org.springframework.web.bind.annotation.PathVariable;
6
import org.springframework.web.bind.annotation.PostMapping;
7
import org.springframework.web.bind.annotation.PutMapping;
8
import org.springframework.web.bind.annotation.RequestBody;
9
import org.springframework.web.bind.annotation.RequestMapping;
10
import org.springframework.web.bind.annotation.ResponseStatus;
11
import org.springframework.web.bind.annotation.RestController;
12
import reactor.core.publisher.Flux;
13
import reactor.core.publisher.Mono;
14
 
          
15
 
          
16
@RestController
17
@RequestMapping("gods")
18
public class GodController {
19
 
          
20
    @Autowired
21
    private GodRepository repository;
22
 
          
23
 
          
24
    @PostMapping
25
    @ResponseStatus(code = HttpStatus.CREATED)
26
    public Mono<String> save(@RequestBody God god) {
27
        return repository.save(god).map(g -> "Saved: " + g.getName());
28
    }
29
 
          
30
    @GetMapping(value = "/{id}", produces = "application/json")
31
    public Mono<God> get(@PathVariable("id") String id) {
32
        return repository.findById(id);
33
    }
34
 
          
35
    @GetMapping(produces = "application/json")
36
    public Flux<God> get() {
37
        return repository.findAll();
38
    }
39
 
          
40
 
          
41
    @PutMapping(value = "/{id}", produces = "application/json")
42
    public Mono<God> update(@PathVariable("id") long id, @RequestBody God god) {
43
        repository.save(god);
44
        return Mono.just(god);
45
    }
46
 
          
47
    @DeleteMapping(value = "/{id}", produces = "application/json")
48
    public Mono<God> delete(@PathVariable("id") String id) {
49
        return repository.findById(id);
50
    }
51
}
52
 
          



Done, we have the code ready to test. You can either install locally or run by Docker. Feel free to peak anyone and test it.

Shell
 




xxxxxxxxxx
1
10


1
curl --location --request POST 'http://localhost:8080/gods' \
2
--header 'Content-Type: application/json' \
3
--data-raw '{"name": "diana", "age": 20, "powers": ["Hunt", "Mon"]}'
4
 
          
5
curl --location --request POST 'http://localhost:8080/gods' \
6
--header 'Content-Type: application/json' \
7
--data-raw '{"name": "apollo", "age": 30, "powers": ["Sun", "Beuty"]}'
8
 
          
9
curl --location --request GET 'http://localhost:8080/gods'
10
 
          
11
#response
12
[
13
    {
14
        "name": "diana",
15
        "age": 20,
16
        "powers": [
17
            "Hunt",
18
            "Mon"
19
        ]
20
    },
21
    {
22
        "name": "apollo",
23
        "age": 30,
24
        "powers": [
25
            "Beuty",
26
            "Sun"
27
        ]
28
    }
29
]
30
 
          



The Java application is ready to go! Let's move it to the cloud easily with Platform.sh. Platform.sh is a second-generation Platform-as-a-Service built especially for continuous deployment.

It allows you to host web applications on the cloud while making your development and testing workflows more productive.

As a Platform as a Service, or PaaS, Platform.sh automatically manages everything your application needs in order to run. That means you can, and should, view your infrastructure needs as part of your application, and version-control it as part of your application.

Every application you deploy on Platform.sh is built as a virtual cluster, containing a set of containers. There are three types of containers within your cluster:

  • One Router (.platform/routes.yaml). Platform.sh allows you to define the routes.
YAML
 




xxxxxxxxxx
1


 
1
"https://{default}/":
2
  type: upstream
3
  upstream: "app:http"
4
 
          
5
"https://www.{default}/":
6
  type: redirect
7
  to: "https://{default}/"
8
 
          



  • Zero or more service containers (.platform/services.yaml). Platform.sh allows you to completely define and configure the topology and services you want to use on your project.
YAML
 




xxxxxxxxxx
1


 
1
mongodb:
2
  type: mongodb:3.6
3
  disk: 512



  • One or more application containers (.platform.app.yaml). You control your application and the way it will be built and deployed on Platform.sh via a single configuration file.

Locally, we don't need to worry about the host, password, user, and so on. We'll overwrite these properties with the MongoDB information that Platform.sh will instantiate and manage to us.

YAML
 




x


1
name: app
2
type: "java:11"
3
disk: 1024
4
hooks:
5
    build: mvn clean install
6
relationships:
7
  database: 'mongodb:mongodb'
8
 
          
9
web:
10
    commands:
11
        start:  |
12
           export USER=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].username"`
13
           export PASSWORD=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].password"`
14
           export HOST=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].host"`
15
           export DATABASE=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].path"`
16
           java -jar -Xmx$(jq .info.limits.memory /run/config.json)m -XX:+ExitOnOutOfMemoryError \
17
           -Dspring.data.mongodb.database=$DATABASE \
18
           -Dspring.data.mongodb.host=$HOST \
19
           -Dspring.data.mongodb.username=$USER \
20
           -Dspring.data.mongodb.password=$PASSWORD \
21
           target/spring-reactive.jar --server.port=$PORT
22
 
          



The application is now ready, so it’s time to move it to the cloud with Platform.sh using the following steps:

  • Create a new free trial account.
  • Sign up with a new user and password, or login using a current GitHub, Bitbucket, or Google account. If you use a third-party login, you’ll be able to set a password for your Platform.sh account later.
  • Select the region of the world where your site should live.
  • Select the blank template.

You have the option to either integrate to GitHub, GitLab, or Platfrom.sh will provide to you. Finally, push to the remote repository:

Shell
 




xxxxxxxxxx
1


 
1
git remote add platform <platform.sh@gitrepository>
2
git commit -m "Initial project"
3
git push -u platform master



Done! We have a simple and nice Spring Webflux application ready to go to the cloud.

Topics:
Reactive MongoDB, cloud, java, mongodb, paas, reactive, spring, spring data, tutorial

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}