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.
Join the DZone community and get the full member experience.
Join For FreeIn 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.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sh.platform.example</groupId>
<artifactId>template-spring-mongodb-reactive</artifactId>
<version>0.0.1</version>
<properties>
<platform.sh.version>2.2.3</platform.sh.version>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-reactive</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>oss.sonatype.org-snapshot</id>
<url>http://oss.sonatype.org/content/repositories/snapshots</url>
</repository>
</repositories>
</project>
The next step is to configure the infrastructure connection, we need to use the @EnableReactiveMongoRepositories
alongside with some infrastructure setup:
x
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories;
public class MongoConfig{
}
We'll create a God entity and then annotated it with @Document
to use it in the database operations.
x
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.Objects;
import java.util.Set;
public class God {
private String name;
private Integer age;
private Set<String> powers;
//getter and setter
}
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.
public interface GodRepository extends ReactiveCrudRepository<God, String> {
}
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.
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.
xxxxxxxxxx
curl --location --request POST 'http://localhost:8080/gods' \
--header 'Content-Type: application/json' \
--data-raw '{"name": "diana", "age": 20, "powers": ["Hunt", "Mon"]}'
curl --location --request POST 'http://localhost:8080/gods' \
--header 'Content-Type: application/json' \
--data-raw '{"name": "apollo", "age": 30, "powers": ["Sun", "Beuty"]}'
curl --location --request GET 'http://localhost:8080/gods'
#response
[
{
"name": "diana",
"age": 20,
"powers": [
"Hunt",
"Mon"
]
},
{
"name": "apollo",
"age": 30,
"powers": [
"Beuty",
"Sun"
]
}
]
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.
xxxxxxxxxx
"https://{default}/":
type upstream
upstream"app:http"
"https://www.{default}/"
type redirect
to"https://{default}/"
- 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.
xxxxxxxxxx
mongodb
type mongodb3.6
disk512
- 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.
x
name app
type"java:11"
disk1024
hooks
build mvn clean install
relationships
database'mongodb:mongodb'
web
commands
start
export USER=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].username"`
export PASSWORD=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].password"`
export HOST=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].host"`
export DATABASE=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].path"`
java -jar -Xmx$(jq .info.limits.memory /run/config.json)m -XX:+ExitOnOutOfMemoryError \
-Dspring.data.mongodb.database=$DATABASE \
-Dspring.data.mongodb.host=$HOST \
-Dspring.data.mongodb.username=$USER \
-Dspring.data.mongodb.password=$PASSWORD \
target/spring-reactive.jar --server.port=$PORT
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:
xxxxxxxxxx
git remote add platform <platform.sh@gitrepository>
git commit -m "Initial project"
git push -u platform master
Done! We have a simple and nice Spring Webflux application ready to go to the cloud.
Opinions expressed by DZone contributors are their own.
Comments