转载

基于 Spring Boot 2.0 的实践: WebFlux 集成 MongoDB

基于 Spring Boot 2.0 的实践: WebFlux 集成 MongoDB

1、理论知识

Spring Boot 2.0 - WebFlux framework

2、基于 Spring Boot 2.0 的实践

① 在 docker 上运行 MongoDB

首先,获取 MongoDB 的镜像:

$ docker pull mongo

然后启动 MongoDB 容器

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

② 构建 Spring Boot 2.0 WebFlux 运行环境

首先,在 IDEA 上新建 Maven 工程,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.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>

        <!-- :heart:不要添加 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>

        <!-- :heart:undertow -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>
        
        <!-- :heart:响应式 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 日志性能之巅

接着,配置 MongoDB,在 application.yml 添加如下内容:

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

小技巧:IDEA 有 MongoDB 的插件,可以方便的查看 MongoDB 里面的数据,插件名字:Mongo Plugin

基于 Spring Boot 2.0 的实践: WebFlux 集成 MongoDB

添加 Spring Boot 启动类:

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 类:

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

}

③ 测试功能

基于 Spring Boot 2.0 的实践: WebFlux 集成 MongoDB

基于 Spring Boot 2.0 的实践: WebFlux 集成 MongoDB

基于 Spring Boot 2.0 的实践: WebFlux 集成 MongoDB

基于 Spring Boot 2.0 的实践: WebFlux 集成 MongoDB

基于 Spring Boot 2.0 的实践: WebFlux 集成 MongoDB

本文由博客一文多发平台 OpenWrite 发布!

原文  https://segmentfault.com/a/1190000022665529
正文到此结束
Loading...