Spring Boot 2.0 - WebFlux With MongoDB

Original link http://www.spring4all.com/article/239

1. Theoretical knowledge

Spring Boot 2.0 - WebFlux framework

2. Practice based on Spring Boot 2.0

① Run MongoDB on docker

First, get an image of MongoDB:

$ docker pull mongo

Then start the MongoDB container

$ docker run -d --name any-mongo -p 27017:27017 mongo

② Build the Spring Boot 2.0 WebFlux runtime environment

First, create a new Maven project on IDEA. The contents of the pom.xml file are as follows:

<?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.anoy</groupId>
    <artifactId>webflux</artifactId>
    <version>1.0-SNAPSHOT</version>

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

    <dependencies>

        <!-- ❤️不要添加 spring-boot-starter-web  -->
        <!-- webflux 支持  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
            <exclusions>
                <!-- 移除 tomcat -->
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
                <!-- 移除默认 logging -->
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- ❤️undertow -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>
        
        <!-- ❤️响应式 MongoDB 支持 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
        </dependency>

        <!-- 代码简化 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!-- 日志 Log4j2 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>

    </dependencies>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

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

</project>

Then, configure Log4j2, refer to the following article: Spring Boot Log4j2 Log Performance Top

Next, configure MongoDB and add the following to application.yml:

spring:
  data:
    mongodb:
      host: localhost
      port: 27017

Tip: IDEA has a plug-in for MongoDB, which can easily view the data in MongoDB. Plug-in name: Mongo Plugin

Mongo Plugin

Add the Spring Boot startup class:

package com.anoy;

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);
    }

}

Add the Person class:

package com.anoy.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {

    @Id
    private Long id;

    private String username;

}

Add PersonRepository, responsible for operating MongoDB:

package com.anoy.repository;

import com.anoy.bean.Person;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;

@Repository
@Primary
public interface PersonRepository extends ReactiveMongoRepository<Person, Long>{

}

Add PersonController , responsible for routing:

package com.anoy.controller;

import com.anoy.bean.Person;
import com.anoy.repository.PersonRepository;
import lombok.AllArgsConstructor;
import org.reactivestreams.Publisher;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
@AllArgsConstructor
public class PersonController {

    private final PersonRepository personRepository;

    /**
     * 正常 MVC 模式
     */
    @GetMapping("/")
    public String hello(){
        return "hello!";
    }

    /**
     * 新增一个 Person
     */
    @PostMapping("/person")
    public Mono<Void> add(@RequestBody Publisher<Person> person){
        return personRepository.insert(person).then();
    }

    /**
     * 根据 ID 查询 Person
     */
    @GetMapping("/person/{id}")
    public Mono<Person> getById(@PathVariable Long id){
        return personRepository.findById(id);
    }

    /**
     * 查询所有 Person
     */
    @GetMapping("/person/list")
    public Flux<Person> list(){
        return personRepository.findAll();
    }

    /**
     * 删除指定 Person
     */
    @DeleteMapping("/person/{id}")
    public Mono<Void> delete(@PathVariable Long id){
        return personRepository.deleteById(id).then();
    }

}

③ Test function

insert data

Data in MongoDB

query all

Query by ID

delete by id

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325445198&siteId=291194637