Vert.x初体验

简介

Vert.x项目起始于2011年,最开始的名字叫做 node.x,是一个仿照Node.js以Java开发的,基于EventLoop的异步非阻塞编程框架。Eclipse Vert.x是一个事件驱动的JVM上的框架,可以帮助我们构建现代、灵活、可扩展的程序。

使用Vert.x

1、新建maven项目,导入依赖

<dependencies>
    <dependency>
        <groupId>io.vertx</groupId>
        <artifactId>vertx-core</artifactId>
        <version>3.2.0</version>
    </dependency>
</dependencies>

2、编写主函数

package com.qianyu;

import io.vertx.core.*;
import io.vertx.core.http.*;

public class Server {
    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        HttpServer httpServer = vertx.createHttpServer();
        httpServer.requestHandler(request -> request.response().end("hello, world"));
        httpServer.listen(8000);
    }
}

此时一个端口为8000的http服务器已经开启

3、在IDEA中编写脚本测试

可以看到,返回字符串hello, world

GET http://localhost:8000

HTTP/1.1 200 OK
Content-Length: 12

hello, world

Response code: 200 (OK); Time: 277ms; Content length: 12 bytes

使用路由

1、导入web模块

<dependency>
    <groupId>io.vertx</groupId>
    <artifactId>vertx-web</artifactId>
    <version>3.2.0</version>
</dependency>

2、使用路由

package com.qianyu;

import io.vertx.core.*;
import io.vertx.core.http.*;
import io.vertx.ext.web.*;

public class Server {
    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        Router router = Router.router(vertx);
        router.get("/demo").blockingHandler(context -> {
            context.response().end("hello, world");
        });
        router.post("/demo").blockingHandler(context -> {
            context.response().end("this is post method");
        });
        HttpServer httpServer = vertx.createHttpServer();
        httpServer.requestHandler(router::accept);
        httpServer.listen(8000);
    }
}

3、使用IDEA编写脚本测试

GET http://localhost:8000/demo

HTTP/1.1 200 OK
Content-Length: 12

hello, world

Response code: 200 (OK); Time: 19ms; Content length: 12 bytes
POST http://localhost:8000/demo

HTTP/1.1 200 OK
Content-Length: 19

this is post method

Response code: 200 (OK); Time: 122ms; Content length: 19 bytes
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值