当前位置: 首页 > news >正文

java webflux函数式实现数据结构

我前面写的文章
java webflux注解方式写一个可供web端访问的数据接口
带大家写了个注解方式实现的webflux

首先 使用函数式时 您需要自己初始化服务器
使用函数式需要两个接口 分别是 RouterFunction 和 HandlerFuncion
RouterFunction主要的作用就是分别一下任务 例如 添加 直接被指派给添加的任务 将任务交到对应的函数上
HandlerFuncion 这是处理请求操作的具体部分 简单说 就是执行你请求具体要做的内容

SpringWebflux请求和响应不再是ServletRequest和ServletResponse ,而是ServerRequest 和 ServerResponse 这两个主要是为了提供非阻塞异步支持的方法

话不多说 上代码
先创建一个 Spring initiolar 项目

然后 找到项目配置文件 pom.xml
引入webflux 和 web
参考代码如下

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

在这里插入图片描述
然后 打开项目如下图箭头所指的这个目录
在这里插入图片描述
在项目创建我们项目所需要的结构包 entity,hondler,senvice
然后 我们的项目就是这样的
在这里插入图片描述
在entity包下创建一个类 叫 User 参考代码如下

package com.example.springapiweb.entity;public class User {private String name;private String gender;private Integer age;public User(String name,String gender,Integer age){this.name = name;this.gender = gender;this.age = age;}public void setName(String name){this.name = name;};public void setGender(String gender) {this.gender = gender;}public void setAge(Integer age) {this.age = age;}public String getName(){return this.name;};public String getGender() {return this.gender;}public Integer getAge() {return this.age;}
}

简单创建了一个实体类 创建了三个字段 name 用户名称 gender 性别 age 年龄 写了他们对应的get set 和 一个有参构造方法

然后呢 我们这个项目就不直接去操作数据库啦

我们在 senvice 包下创建一个接口 叫 UserService
参考代码如下

package com.example.springapiweb.senvice;import com.example.springapiweb.entity.User;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;public interface UserService {//根据id查询用户Mono<User> getUserById(int id);//查询所有用户Flux<User> getAllUser();//添加用户Mono<Void> saveUserInfo (Mono<User> user);
}

我们在接口中定义了几个比较简单的用户操作方法

然后在 senvice 下创建一个包 叫 impl 用于存放实现类 在下面创建一个类 叫 UserServiceImpl

参考代码如下

package com.example.springapiweb.senvice.impl;import com.example.springapiweb.entity.User;
import com.example.springapiweb.senvice.UserService;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;import java.util.Map;
import java.util.HashMap;@Repository
public class UserServiceImpl implements UserService {//创建map集合存储教据private final Map<Integer,User> users = new HashMap<>();//在构造方法中为map注入几条数据public UserServiceImpl(){this.users.put(1,new User("小猫猫","女",2));this.users.put(2,new User("小明","男",11));this.users.put(3,new User("服部半藏","男",32));}//根据id查询指定用户@Overridepublic Mono<User> getUserById(int id) {return Mono.justOrEmpty(this. users. get (id));}//查询所有用户@Overridepublic Flux<User> getAllUser() {return Flux.fromIterable(this.users.values());}//添加用户@Overridepublic Mono<Void> saveUserInfo(Mono<User> userMono) {return userMono.doOnNext(person -> {//向map集合里面放值int id = users. size()+1;users.put(id,person);}).thenEmpty(Mono.empty());}
}

然后在hondler下创建一个类 叫 UserHandler
参考代码如下

package com.example.springapiweb.hondler;import com.example.springapiweb.entity.User;
import com.example.springapiweb.senvice.UserService;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;import static org.springframework.web.reactive.function.BodyInserters.fromObject;public class UserHandler {private final UserService userService;public UserHandler(UserService userService) {this.userService = userService;}//根据id查询用户public Mono<ServerResponse> getUserById(ServerRequest request){int userid = Integer.valueOf(request.pathVariable("id"));Mono<User> userMono = this.userService.getUserById(userid);return userMono.flatMap(person -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(fromObject(person)));}//查询所有用户public Mono<ServerResponse> getAllUsers (ServerRequest request) {Flux<User> users = this. userService.getAllUser();return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(users,User.class);}//添加用户public Mono<ServerResponse> saveUser(ServerRequest request) {Mono<User> userMono = request.bodyToMono(User.class);return ServerResponse.ok().build(this.userService.saveUserInfo(userMono));}}

ServerRequest 是一个函数式请求对象 从里面可以调用pathVariable 拿到请求路径上的参数 这里 我们拿一个叫id的参数 然后调用userService中的getUserById 拿到一个user类的对象 通过id取回来的 然后通过步骤 转为json

那么 这样 整体的一个结构我们就搭好了

下面 我们要通过 RouterFunction 做路由 来进行一个调用

然后在src下创建一个类 叫 Server 参考代码如下

package com.example.springapiweb;import com.example.springapiweb.hondler.UserHandler;
import com.example.springapiweb.senvice.UserService;
import com.example.springapiweb.senvice.impl.UserServiceImpl;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
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.netty.http.server.HttpServer;import java.io.IOException;import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;public class Server {public static void main(String[] args) throws IOException {Server server = new Server();server.createReactorServer();System.out.println("enter to exit");System.in.read();}//1创建Router路由public RouterFunction<ServerResponse> routingFunction() {UserService userService = new UserServiceImpl();UserHandler handler = new UserHandler(userService);return RouterFunctions.route(GET("/users/{id}").and(accept(APPLICATION_JSON)),handler::getUserById).andRoute(GET( "/users").and(accept(APPLICATION_JSON)),handler::getAllUsers);}public void createReactorServer() {RouterFunction<ServerResponse> route = routingFunction();HttpHandler httpHandler = toHttpHandler(route);ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);HttpServer httpServer = HttpServer. create();httpServer.handle(adapter).bindNow();}
}

我们这个要靠main执行 在main上右键 选择启动
在这里插入图片描述
然后项目就起来了 我们拿到系统给的端口
在这里插入图片描述

直接访问 http://localhost:端口/users/1
例如我这里 运行结果如下
在这里插入图片描述
这里 我们访问的就是 id为1的用户啦
然后 我们试所有用户
在这里插入图片描述
也没有任何问题

http://www.lryc.cn/news/44017.html

相关文章:

  • 百度文心一言可以完胜ChatGPT的4点可能性
  • 大型分布式架构设计
  • 基于springboot实现校园在线拍卖电商系统【源码】
  • SaaS智慧校园源码,电子班牌管理系统 人脸考勤、综合评价系统、请假管理、校务管理
  • MONGODB mongodb 一般人不知道的数据类型与使用
  • 蚁群算法优化
  • 山东首版次申报的材料
  • 个人时间管理网站—首页的前端实现【源码】
  • Python毕业设计推荐
  • 使用nodemon时报错:“无法加载文件...,因为在此系统上禁止运行脚本“;windows执行策略修改
  • 网络协议分析期末复习(五)
  • 外贸找客户软件:Yellow Page Spider 8.7.1 Crack
  • 博客管理系统(前端页面设计)
  • 安装yolov5环境
  • IP 归属地查询 API 教你从0到1顺着网线找到键盘侠
  • 【K8S系列】深入解析Pod对象(二)
  • 从3千到3万,我的测试之路真的坎坷
  • linux下使用system函数在程序中运行linux的shell命令
  • 银行数字化转型导师坚鹏:银行业发展趋势及对人才的需求分析
  • NFS挂载
  • IDEA使用技巧
  • 自动化测试之一【接口测试总结】
  • 科大奥瑞物理实验——傅里叶光学
  • mysql count(*)的性能如何?
  • gan实战(基础GAN、DCGAN)
  • 使用C语言实现服务器/客户端的TCP通信
  • AI模型训练推理一定要知道的事情
  • SPSS27破解安装后,出现应用程序无法正常启动(0xc000007b)
  • 央企程序员写了重大bug,会造成用户个人信息泄露,领导已经知道了,需要赶紧跑路吗?...
  • day14—选择题