【转】Building a Reactive RESTful Web Service - 用 SpringBoot WebFlux 构建reactive restful web服务

【From】https://spring.io/guides/gs/reactive-rest-service/

Building a Reactive RESTful Web Service —— 用 Spring WebFlux 构建reactive restful web服务

本文转自以上Pivotal公司原文,简要概括翻译。

使用spring framework 5 里面的webflux来构建restful web服务。本人实测使用环境是JDK1.8,springboot 2.2.1.RELEASE,gradle 5.2.1,IntelliJ IDEA 2019。

一、创建项目

在IDE里创建一个新的gradle项目,例如取名“webflux_greeting”。在IDEA中建好项目会自己构建这个空项目,然后一直显示“configuring build...”,应该是一直连不了maven的官方仓库的问题,我直接关了。下面修改完build.gradle之后加上阿里云的maven仓库,再构建就好。

二、配置build.gradle

使用以下内容替换自动生成的build.gradle文件,buildscript里面的仓库信息是给gradle下载自己的依赖用的,buildscript后面的repositories才是项目构建时查找依赖的仓库地址,两个都加上阿里云仓库作为优先选择。

buildscript {
    ext {
        springBootVersion = '2.2.1.RELEASE'
    }
    repositories {
maven { url "http://maven.aliyun.com/nexus/content/groups/public/" } mavenCentral() } dependencies { classpath(
"org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' bootJar { baseName = 'gs-reactive-rest-service' version = '0.1.0' } sourceCompatibility = 1.8 repositories {
maven { url "http://maven.aliyun.com/nexus/content/groups/public/" } mavenCentral() } dependencies { compile(
'org.springframework.boot:spring-boot-starter-webflux') testCompile('org.springframework.boot:spring-boot-starter-test') testCompile('io.projectreactor:reactor-test') }

Spring Boot gradle 插件提供了以下好处:

a、会自动收集所有需要的jar,打包成一个uber-jar,即集成所有依赖包。

b、自动识别所有 “public static void main()” 方法,并标记成可执行类。

c、自动解决项目中和springboot的引用相关的版本依赖和冲突,你也可以手动指定依赖版本。

三、编写WebFlux Handler

在IDEA的项目名上右键,选择添加目录,然后会弹出快捷方式。选择创建“src/main/java”目录,再在目录下添加包“hello”,然后创建一个文件 GreetingHandler.java:

package hello;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;

import reactor.core.publisher.Mono;

@Component
public class GreetingHandler {

  public Mono<ServerResponse> hello(ServerRequest request) {
    return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)
      .body(BodyInserters.fromObject("Hello, Spring!"));
  }
}

猜你喜欢

转载自www.cnblogs.com/pekkle/p/12240100.html