响应式编程WebFlux

一、WebFlux简介

SpringBoot2.x底层使用的Spring5Spring5推出了响应式编程Spring WebFlux

WebFlux特点:

​ ①SpringMVC是同步阻塞的IO模型,资源浪费相对来说比较严重。而WebFlux就可以做到异步非阻塞。

​ ②事件驱动(Event-driven),就像和VueAngular一样,各个相关联的值会相应的动态变化。

​ ③SpringMVC项目均需要运行在Servlet容器上如Tomcat, Jetty…而现WebFlux不仅能运行于传统的Servlet容器中(需要支持Servlet3.1),还能运行在支持NIONettyUndertow中。

二、WebFlux入门

①引入WebFlux依赖,引入了webflux就不引入spring-boot-starter-web,因为spring-boot-starter-web的优先级更高。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

②启动方式默认是Netty,8080端口。

③代码编写

​ 因为如果是要达到异步非阻塞的效果,数据库也应换为innoDB型数据库,这里使用静态变量模拟数据库。

public class User {
    private long id ;
    private String name;
}   
@Service
public class UserService {

    private static final Map<Integer, User> dataMap = new HashMap<>();

    static {
        dataMap.put(1,new User(1,"a"));
        dataMap.put(2,new User(2,"b"));
        dataMap.put(3,new User(3,"c"));
        dataMap.put(4,new User(4,"d"));
    }

    /**
     * 返回所有用户
     */
    public Flux<User> getAllUser(){
        Collection<User> users = dataMap.values();
        return Flux.fromIterable(users);
    }

    /**
     * 返回具体用户
     */
    public Mono<User> getUserById(int id){
        User user = dataMap.get(id);
        return Mono.justOrEmpty(user);
    }
}
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 返回指定用户额
     */
    @RequestMapping("/{id}")
    public Mono<User> getUserById(@PathVariable int id){
        return userService.getUserById(id);
    }

    /**
     * 返回所有用户
     */
    @RequestMapping("/all")
    public Flux<User> getAllUsers(){
        return userService.getAllUser();
    }

    /**
     * 延迟返回用户
     * produces控制服务器返回客户端的格式
     */
    @RequestMapping(value = "/delay",produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
    public Flux<User> getAllUsersDelay(){
        return userService.getAllUser().delayElements(Duration.ofSeconds(2));
    }
}

④说明

Mono 表示的是包含 0 或者 1 个元素的异步序列,为单一对象

Flux表示的是包含 0 到 N 个元素的异步序列,为数组列表对象

Spring WebFlux应用程序不严格依赖于Servlet API,因此它们不能作为war文件部署,也不能使用src/main/webapp目录。

Spring WebFlux支持各种模板技术,包括ThymeleafFreeMarker

三、Mono、Flux的API解释

发布了81 篇原创文章 · 获赞 124 · 访问量 38万+

猜你喜欢

转载自blog.csdn.net/qq_38697437/article/details/104653025