持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第19天,点击查看活动详情
上一期说到了sentinel,这期讲一讲WebFlux
我们都知道。gateway基于spring5构建,能够实现响应式非阻塞api,支持长链接,更好地支持spring体系产品,依赖的就是springboot的webflux。 在Gateway配置类中,GatewayClassPathWarningAutoConfiguration中首先检查了是否依赖于springboot的webflux。
那webflux是什么呢? 官网给的解释是: Spring WebFlux is a non-blocking web framework built from the ground up to take advantage of multi-core, next-generation processors and handle massive numbers of concurrent connections.
通过在线翻译,转换成中文
WebFlux 内部使用的是响应式编程(Reactive Programming),以 Reactor 库为基础, 基于异步和事件驱动,可以让我们在不扩充硬件资源的前提下,提升系统的吞吐量和伸缩性。
最最最重要的作用就是提升系统的吞吐量和伸缩性。
因为Spring WebFlux 是一个异步非阻塞式的 Web 框架。所以特别适合在微服务这种网络IO特别密集的服务中。
从上图可以看出Spring MVC和Spring WebFlux的异同点。他们都可以使用@Controller注解。可以使用 Tomcat, Jetty, Undertow Servlet 容器。Spring MVC 的前端控制器是 DispatcherServlet, 而 WebFlux 是 DispatcherHandler,它实现了 WebHandler 接口。
我们再看看代码的应用。
- 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
package com.lijianb.springWebFlux.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import com.lijianb.springWebFlux.entity.User;
@RestController
public class getWebFluxController {
@GetMapping("/get")
public String get() {
return "getWebFlux !";
}
@GetMapping("/user")
public Mono<User> getUser() {
User user = new User();
user.setAge("11");
return Mono.just(user);
}
}
package com.lijianb.springWebFlux.entity;
public class User {
private String age;
public String getAge() {
return name;
}
public String setAge(String age) {
this.age = age
}
}
在前台直接访问接口,/get接口时,会在客户端直接显示getWebFlux,访问/user接口时,会在客户端返回json格式的对象{"age","11"}。表示我们成功的使用webFlux返回了该对象数据。
在 WebFlux 中,Mono 是非阻塞的写法,用Mono包裹一个对象或者Flux包裹List集合,发挥出 WebFlux 非阻塞 + 异步的特性。