DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Introduction to Spring Data Elasticsearch 4.1
  • Manage Hierarchical Data in MongoDB With Spring
  • Spring Data: Data Auditing Using JaVers and MongoDB
  • Have You Heard About Cloud Native Buildpacks?

Trending

  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Testing SingleStore's MCP Server
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • Automating Data Pipelines: Generating PySpark and SQL Jobs With LLMs in Cloudera
  1. DZone
  2. Data Engineering
  3. Databases
  4. Intro to Spring Data MongoDB Reactive and How to Move It to the Cloud

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.

By 
Otavio Santana user avatar
Otavio Santana
DZone Core CORE ·
Updated Jan. 26, 22 · Tutorial
Likes (8)
Comment
Save
Tweet
Share
37.5K Views

Join the DZone community and get the full member experience.

Join For Free

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 through 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
 




x


 
1
@Repository
2
public interface GodRepository extends ReactiveCrudRepository<God, String> {
3

          
4
}



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

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

Java
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;


@RestController
@RequestMapping("gods")
public class GodController {

    @Autowired
    private GodRepository repository;


    @PostMapping
    @ResponseStatus(code = HttpStatus.CREATED)
    public Mono<String> save(@RequestBody God god) {
        return repository.save(god).map(g -> "Saved: " + g.getName());
    }

    @GetMapping(value = "/{id}", produces = "application/json")
    public Mono<God> get(@PathVariable("id") String id) {
        return repository.findById(id);
    }

    @GetMapping(produces = "application/json")
    public Flux<God> get() {
        return repository.findAll();
    }


    @PutMapping(value = "/{id}", produces = "application/json")
    public Mono<God> update(@PathVariable("id") long id, @RequestBody God god) {
        repository.save(god);
        return Mono.just(god);
    }

    @DeleteMapping(value = "/{id}", produces = "application/json")
    public Mono<Void> delete(@PathVariable("id") String id) {
        return repository.deleteById(id);
    }
}


Done, we have the code ready to test. You can either install it locally or run it by Docker. Feel free to pick 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.

Spring Data Data processing Cloud MongoDB Spring Framework application Docker (software) Reactive programming

Opinions expressed by DZone contributors are their own.

Related

  • Introduction to Spring Data Elasticsearch 4.1
  • Manage Hierarchical Data in MongoDB With Spring
  • Spring Data: Data Auditing Using JaVers and MongoDB
  • Have You Heard About Cloud Native Buildpacks?

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!