WebFlux从入门到精通(1)

WebFlux之HelloWorld

此次开发工具使用idea,jdk11

  1. 打开idea

  2. file -> new -> project 进入下面的界面,使用SpringInitialzr构建一个spirngboot项目
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

  3. 构建出一个基于webflux的项目
    在这里插入图片描述

  4. 现在开始编写第一个helloworld
    在这里插入图片描述

package com.example.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldController {

   static final String HELLO_WORLD = "Hello World";

   @GetMapping
   public String hello(){
       return HELLO_WORLD;
   }
}

  1. 运行这个application
    在这里插入图片描述
    6.通过查看application启动监听的端口是8080,我们现在通过浏览器访问8080端口
    在这里插入图片描述
    可以到,helloworld已经成功显示了,但是上面的案例可以看出来,它好像和原来的mvc没什么区别,所以现在我们来改造一下这个项目,将代码修改成下面的样子
package com.example.controller;

import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.stream.IntStream;

@RestController
public class HelloWorldController {

    static final String HELLO_WORLD = "Hello World";

    @GetMapping
    public String hello(){
        return HELLO_WORLD;
    }

    /**
     * 将数据转换成流的方式输出
     * Mono是单条数据,Flux一般处理集合或者数组
     * @return
     */
    @GetMapping("/hello1")
    public Mono<String> hello1(){
        return Mono.just(HELLO_WORLD);
    }

    /**
     *  MediaType.TEXT_EVENT_STREAM_VALUE 设置这个头部是让flux变成响应式的
     *  如果不设置这个参数,flux就相当于List Array
     * @return
     */
    @GetMapping(value = "/hellon",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> hellon(){
        return Flux
                .fromStream(IntStream.range(1,20).mapToObj(item ->HELLO_WORLD + item))
                .doOnNext(item -> {
                    try {
                        //等待500毫秒响应一次数据
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
    }

    /**
     * 定义一个路由函数
     * @return
     */
    @Bean
    public RouterFunction<ServerResponse> function(){
        return RouterFunctions.route(
                RequestPredicates.GET("/helloF"),
                serverRequest -> {
                    return ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON).bodyValue(HELLO_WORLD);
                }
        );
    }
}

通过改造之后,发现webflux有不同方式响应数据,下一次,我会讲webflux如何整合thymeleaf,实现一个登陆注册个功能

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Spring WebFluxSpring Framework 5引入的新的响应式Web框架,它基于Reactor项目实现了响应式编程模型。相比于传统的Spring MVC框架,Spring WebFlux提供了更好的吞吐量和更低的延迟,适用于高并发场景。 下面是一个快速入门的示例: 1. 创建一个Spring Boot项目,选择Webflux和Reactive MongoDB依赖。 2. 创建一个数据模型类,比如User: ```java public class User { private String id; private String name; private int age; // 省略getter和setter } ``` 3. 创建一个数据访问层接口和实现,使用ReactiveMongoRepository来实现MongoDB的数据访问: ```java public interface UserRepository extends ReactiveMongoRepository<User, String> { } @Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public Mono<User> save(User user) { return userRepository.save(user); } public Mono<User> findById(String id) { return userRepository.findById(id); } public Flux<User> findAll() { return userRepository.findAll(); } public Mono<Void> deleteById(String id) { return userRepository.deleteById(id); } } ``` 4. 创建一个控制器类,定义接口: ```java @RestController @RequestMapping("/users") public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } @PostMapping("") public Mono<User> save(@RequestBody User user) { return userService.save(user); } @GetMapping("/{id}") public Mono<User> findById(@PathVariable String id) { return userService.findById(id); } @GetMapping("") public Flux<User> findAll() { return userService.findAll(); } @DeleteMapping("/{id}") public Mono<Void> deleteById(@PathVariable String id) { return userService.deleteById(id); } } ``` 5. 启动应用程序,访问http://localhost:8080/users即可测试。 以上就是一个简单的Spring WebFlux入门示例,希望对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值