ZetCode

Spring Boot MongoDB Reactive

最后修改于 2023 年 7 月 16 日

Spring Boot MongoDB Reactive 教程展示了如何在 Spring Boot 应用程序中使用 MongoDB 进行响应式编程。

MongoDB

MongoDB 是一个 NoSQL 跨平台面向文档的数据库。它是目前最流行的数据库之一。MongoDB 由 MongoDB Inc. 开发,并作为免费和开源软件发布。

Spring Data MongoDB 项目提供了与 MongoDB 文档数据库的集成。

响应式编程

响应式编程 是一种编程范式,它具有函数式、基于事件、非阻塞、异步和以数据流处理为中心。 术语“响应式”源于我们对变化的反应,例如鼠标点击或 I/O 事件。

当我们处理大量流数据时,响应式应用程序的扩展性更好,效率也更高。 响应式应用程序是非阻塞的; 它们不使用资源等待进程完成。

构建响应式应用程序时,我们需要它一直到数据库都是响应式的。 我们需要使用支持响应式编程的数据库。 MongoDB 是一个具有响应式支持的数据库。

响应式应用程序实现基于事件的模型,数据被推送到使用者。 数据的消费者被称为订阅者,因为它订阅发布者,发布者发布异步的数据流。

Spring Reactor

Spring Reactor 是一个用于在 JVM 上构建非阻塞应用程序的响应式库,基于 Reactive Streams 规范。

Reactor 项目提供了两种类型的发布者:MonoFluxFlux 是一个发布者,它产生 0 到 N 个值。 返回多个元素的操作使用此类型。 Mono 是一个发布者,它产生 0 到 1 个值。 它用于返回单个元素的操作。

Spring Boot MongoDB Reactive 示例

在下面的应用程序中,我们使用响应式编程与 MongoDB 数据库。

注意: 默认情况下,在没有任何特定配置的情况下,Spring Boot 尝试连接到本地托管的 MongoDB 实例,使用 test 数据库名称。
pom.xml
src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           │   Application.java
│   │           │   MyRunner.java
│   │           ├───model
│   │           │       City.java
│   │           ├───repository
│   │           │       CityRepository.java
│   │           └───service
│   │                   CityService.java
│   │                   ICityService.java
│   └───resources
│           application.properties
└───test
    └───java

这是 Spring 应用程序的项目结构。

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zetcode</groupId>
    <artifactId>springbootmongodbreactive</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.7</version>
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.6.7</version>
            </plugin>
        </plugins>
    </build>

</project>

这是 Maven pom.xml 文件。 spring-boot-starter-data-mongodb-reactive 是一个 Spring Boot 启动器,用于使用 MongoDB 面向文档的数据库和 Spring Data MongoDB Reactive。

resources/application.properties
spring.main.banner-mode=off

application.properties 中,我们关闭 Spring Boot 横幅并设置日志属性。 Spring Boot 默认尝试连接到本地托管的 MongoDB 实例,使用 test 数据库。

# mongodb
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=testdb

如果我们想配置 MongoDB,我们可以设置相应的属性。

com/zetcode/model/City.java
package com.zetcode.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import java.util.Objects;

@Document(value="cities")
public class City {

    @Id
    private String id;

    private String name;
    private int population;

    public City() {
    }

    public City(String name, int population) {
        this.name = name;
        this.population = population;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 79 * hash + Objects.hashCode(this.id);
        hash = 79 * hash + Objects.hashCode(this.name);
        hash = 79 * hash + this.population;
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final City other = (City) obj;
        if (this.population != other.population) {
            return false;
        }
        if (!Objects.equals(this.name, other.name)) {
            return false;
        }
        return Objects.equals(this.id, other.id);
    }

    @Override
    public String toString() {

        var builder = new StringBuilder();
        builder.append("City{id=").append(id).append(", name=")
                .append(name).append(", population=")
                .append(population).append("}");

        return builder.toString();
    }
}

这是 City bean,它有三个属性:idnamepopulation

@Document(value="cities")
public class City {

该 bean 使用可选的 @Document 注解进行修饰。

@Id
private String id;

id 使用 @Id 注解进行修饰。 Spring 自动为新生成的城市对象生成一个新的 id。

com/zetcode/repository/CityRepository.java
package com.zetcode.repository;

import com.zetcode.model.City;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;

@Configuration
public interface CityRepository extends ReactiveMongoRepository<City, String> {
}

通过继承 ReactiveMongoRepository,我们拥有一个响应式的 MongoDB 存储库。

com/zetcode/service/ICityService.java
package com.zetcode.service;

import com.zetcode.model.City;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

public interface ICityService {

    Mono<City> insert(City city);
    Flux<City> saveAll(List<City> cities);
    Mono<City> findById(String id);
    Flux<City> findAll();
    Mono<Void> deleteAll();
}

ICityService 包含五个契约方法。

com/zetcode/MyRunner.java
package com.zetcode;

import com.zetcode.model.City;
import com.zetcode.service.CityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class MyRunner implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(MyRunner.class);

    @Autowired
    private CityService cityService;

    @Override
    public void run(String... args) throws Exception {

        logger.info("Creating cities");

        var cities = List.of(new City("Bratislava", 432000),
                new City("Budapest", 1759000),
                new City("Prague", 1280000),
                new City("Warsaw", 1748000));

        Mono<Void> one = cityService.deleteAll();

        Flux<City> two = cityService.saveAll(cities);
        Flux<City> three = cityService.findAll();
        three.subscribe(city -> logger.info("{}", city));

        Mono<Void> all = Mono.when(one, two, three);
        all.block();
    }
}

我们有一个命令行运行器。 在它的 run 方法中,我们使用响应式编程访问 MongoDB。

Mono<Void> one = cityService.deleteAll();

如果集合中有任何城市,我们将删除所有城市。

Flux<City> two = cityService.saveAll(cities);

我们保存一个城市列表。

Flux<City> three = cityService.findAll();
three.subscribe(System.out::println);

我们从集合中查找所有城市。 我们使用 subscribe 方法订阅发布者,并将检索到的城市打印到终端。

Mono<Void> all = Mono.when(one, two, three);

使用 Mono.when,我们将三个发布者聚合到一个新的 Mono 中,当所有源都完成后,Mono 将被满足。

all.block();

使用 block,我们触发所有三个操作并等待完成。 由于我们有一个控制台应用程序,我们引入了一个阻塞操作,以便在终端上获取结果。

subscribe 方法立即启动工作并返回。 我们不能保证在应用程序的其他部分运行时操作已完成。 block 是一个阻塞操作:它触发操作并等待其完成。

注意: 通常,我们在应用程序中很少使用阻塞调用。 控制台应用程序中的操作是少数例外之一。

com/zetcode/Application.java
package com.zetcode;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application  {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

此代码设置了 Spring Boot 应用程序。

在本文中,我们学习了如何在 Spring Boot 应用程序中使用响应式编程模型来编程 MongoDB。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出 所有 Spring Boot 教程