Spring Boot 2.0 - WebFlux With MongoDB

原文連接 http://www.spring4all.com/article/239react

一、理論知識

Spring Boot 2.0 - WebFlux frameworkweb

二、基於 Spring Boot 2.0 的實踐

① 在 docker 上運行 MongoDB

首先,獲取 MongoDB 的鏡像:spring

$ docker pull mongo

而後啓動 MongoDB 容器mongodb

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

② 構建 Spring Boot 2.0 WebFlux 運行環境

首先,在 IDEA 上新建 Maven 工程,pom.xml 文件內容以下:docker

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

而後,配置 Log4j2,參考以下文章: Spring Boot Log4j2 日誌性能之巔apache

接着,配置 MongoDB,在 application.yml 添加以下內容:tomcat

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

小技巧:IDEA 有 MongoDB 的插件,能夠方便的查看 MongoDB 裏面的數據,插件名字:Mongo Pluginapp

Mongo Plugin

添加 Spring Boot 啓動類:maven

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

}

添加 Person 類:spring-boot

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;

}

添加 PersonRepository,負責操做 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>{

}

添加 PersonController , 負責路由:

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

}

③ 測試功能

插入數據

MongoDB 中的數據

查詢全部

根據 ID 查詢

根據 ID 刪除

相關文章
相關標籤/搜索