博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring webflux 函数式编程web框架
阅读量:6998 次
发布时间:2019-06-27

本文共 5330 字,大约阅读时间需要 17 分钟。

Spring webflux

Spring 5.0 Spring webflux 是一个全新的非堵塞的函数式 Reactive Web 框架,可以用来构建异步的、非堵塞的、事件驱动的服务。 springboot2.0发布不久,最近研究了一下springboot2.0的新特性,其中就发现了webflux。

下面是spring-flux的一个demo话不多少上代码

使用webflux和MVC的区别就是在artifacId后面加上flux

org.springframework.boot
spring-boot-starter-parent
2.0.0.RELEASE
org.springframework.boot
spring-boot-starter-webflux
复制代码
@RestControllerpublic class HelloController {	@GetMapping("/hello")	public String hello() {		return "hello world";	}}复制代码

在webflux中有Handler和Router 的概念,分别与springmvc中的controllerr和equest mapper相对应,通俗的将就是handler就是真正处理请求的bean,可以在handler中编写处理请求的逻辑,而Router就是如何让请求找到对应的handler中的方法处理,下面我们来实现一个简单的handler和router。

@Componentpublic class HelloWorldHandler {    public Mono
helloWorld(ServerRequest request){ return ServerResponse.ok() .contentType(MediaType.TEXT_PLAIN) .body(BodyInserters.fromObject("hello flux")); } }复制代码

上面是一个简单的handler只相应了一个“hello flux” 字符串!

@Configurationpublic class RouterConfig {    @Autowired    private HelloWorldHandler helloWorldHandler;    @Bean    public RouterFunction
helloRouter() { return RouterFunctions.route(RequestPredicates.GET("/hello"), helloWorldHandler::helloWorld); }}复制代码

上面是对应的router对应的是匹配一个get方式的/hello请求,然后调用helloWorldHandler中的helloWorld方法向浏览器输出一个文本类型的字符串

再来一个例子

@Componentpublic class UserHandler {    @Autowired    private ReactiveRedisConnection connection;    public Mono
getTime(ServerRequest request) { return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN) .body(Mono.just("Now is " + new SimpleDateFormat("HH:mm:ss").format(new Date())), String.class); } public Mono
getDate(ServerRequest request) { return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN) .body(Mono.just("Today is " + new SimpleDateFormat("yyyy-MM-dd").format(new Date())), String.class); } public Mono
sendTimePerSec(ServerRequest request) { return ServerResponse.ok().contentType(MediaType.TEXT_EVENT_STREAM) .body(Flux.interval(Duration.ofSeconds(1)).map(l -> new SimpleDateFormat("HH:mm:ss").format(new Date())), String.class); } public Mono
register(ServerRequest request) { Mono
body = request.bodyToMono(Map.class); return body.flatMap(map -> { String username = (String) map.get("username"); String password = (String) map.get("password"); String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt()); return connection.stringCommands() .set(ByteBuffer.wrap(username.getBytes()), ByteBuffer.wrap(hashedPassword.getBytes())); }).flatMap(aBoolean -> { Map
result = new HashMap<>(); ServerResponse serverResponse = null; if (aBoolean){ result.put("message", "successful"); return ServerResponse.ok() .contentType(MediaType.APPLICATION_JSON_UTF8) .body(BodyInserters.fromObject(result)); }else { result.put("message", "failed"); return ServerResponse.status(HttpStatus.BAD_REQUEST) .contentType(MediaType.APPLICATION_JSON_UTF8) .body(BodyInserters.fromObject(request)); } }); } public Mono
login(ServerRequest request) { Mono
body = request.bodyToMono(Map.class); return body.flatMap(map -> { String username = (String) map.get("username"); String password = (String) map.get("password"); return connection.stringCommands().get(ByteBuffer.wrap(username.getBytes())).flatMap(byteBuffer -> { byte[] bytes = new byte[byteBuffer.remaining()]; byteBuffer.get(bytes, 0, bytes.length); String hashedPassword = null; try { hashedPassword = new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } Map
result = new HashMap<>(); if (hashedPassword == null || !BCrypt.checkpw(password, hashedPassword)) { result.put("message", "账号或密码错误"); return ServerResponse.status(HttpStatus.UNAUTHORIZED) .contentType(MediaType.APPLICATION_JSON_UTF8) .body(BodyInserters.fromObject(result)); } else { result.put("token", "无效token"); return ServerResponse.ok() .contentType(MediaType.APPLICATION_JSON_UTF8) .body(BodyInserters.fromObject(result)); } }); }); }}复制代码
@Configurationpublic class RouterConfig {    @Autowired    private HelloWorldHandler helloWorldHandler;    @Bean    public RouterFunction
helloRouter() { return RouterFunctions.route(RequestPredicates.GET("/hello"), helloWorldHandler::helloWorld); } @Autowired private UserHandler userHandler; @Bean public RouterFunction
timerRouter() { return RouterFunctions.route(RequestPredicates.GET("/time"), userHandler::getTime) .andRoute(RequestPredicates.GET("/date"), userHandler::getDate); } @Bean public RouterFunction
routerFunction() { return RouterFunctions.route(RequestPredicates.GET("/hello"), helloWorldHandler::helloWorld) .andRoute(RequestPredicates.POST("/register"), userHandler::register) .andRoute(RequestPredicates.POST("/login"), userHandler::login) .andRoute(RequestPredicates.GET("/times"), userHandler::sendTimePerSec); }}复制代码

转载于:https://juejin.im/post/5cbae38ee51d456e5977b185

你可能感兴趣的文章
蚂蚁金服mPaaS 3.0发布 助力客户智能化构建超级App生态
查看>>
如何实现全屏遮罩(附Vue.extend和el-message源码学习)
查看>>
阿里:千亿交易背后的0故障发布
查看>>
利用angular4和nodejs-express构建一个简单的网站(十)—好友模块
查看>>
极光大数据告诉你,程序员们都在"愁"些啥?
查看>>
前端基础知识学习记录(三)
查看>>
LeanCloud + Ionic3 迅速重构应用
查看>>
chrome扩展推荐:帮你留住每一次ctrl+c --- Clipboard History 2
查看>>
Spring Web Services 3.0.4.RELEASE和2.4.3.RELEASE发布
查看>>
配置一次,到处运行:将配置与运行时解耦
查看>>
菜鸟成都未来园区启动,无人车首次进入园区调拨运输环节 ...
查看>>
算法不扎实的程序员,每个都很慌
查看>>
Element 2.6.3 发布,基于 Vue 2.0 的桌面端组件库
查看>>
基于kubeadm的kubernetes高可用集群部署
查看>>
定位「数字化助手」,腾讯想用服务创新助力产业智慧升级
查看>>
golang之sync.Mutex互斥锁源码分析
查看>>
SAP增强的PA教材内容
查看>>
C#使用Xamarin开发可移植移动应用(3.Xamarin.Views控件)附源码
查看>>
Java 模拟基于UDP的Socket通信
查看>>
有关 Windows Lite 的一切,只为对抗 Chrome OS?
查看>>