quarkus学习之Vertx-Web(九)

看网上有人评论,写Vertx更像一个程序员,spring更像是在搬砖
稍微了解了一下Vertx,发现还是有很多特性的,主要感兴趣的几个记录下来

Vertx,是一个基于JVM、轻量级、高性能的应用平台,非常适用于移动端后台、互联网、企业应用架构。

Vertx,基于Netty全异步通信,并扩展出了很多有用的特性。

Vertx,是基于事件总线设计的高性能架构,保证应用中不同部分以一种非堵塞的线程安全方式通讯。


异步无锁编程 
经典的多线程编程模型能满足很多Web开发场景,但随着移动互联网并发连接数的猛增,多线程并发控制模型性能难以扩展,
同时要想控制好并发锁需要较高的技巧,目前Reactor异步编程模型开始跑马圈地,而Vert.x就是这种异步无锁编程的一个首选。

高并发性
vert.x是一个事件驱动非阻塞的异步编程框架,你可以在极少的核心线程里占用最小限度的硬件资源处理大量的高并发请求。
此并发并非JDK库的并发,当你Coding的时候,不再关注其锁,同步块,死锁之类的概念,你就可以随性所欲的写自己的业务逻辑,Vert.x本身内置三种线程池帮你处理。

整合一下,引入依赖


    io.quarkus
    quarkus-vertx-web

测试代码RouteController

@ApplicationScoped
public class RouteController {

    @Route(path = "/hello" ,methods = HttpMethod.GET)
    public void handler(RoutingContext routingContext){
        String name = routingContext.request().getParam("name");
        routingContext.response().end("hello");
    }

    @Route.Routes ({
        @Route(path = "/route01" ,methods = HttpMethod.GET),
        @Route(path = "/route02" ,methods = HttpMethod.GET)
    })
    public void routes(RoutingContext routingContext){
        routingContext.response().end("hello route");
    }

    @Route(path = "/login",methods = HttpMethod.POST)
    public void login(RoutingContext routingContext){
        @Nullable String username = routingContext.request().getFormAttribute("username");
        @Nullable String password = routingContext.request().getFormAttribute("password");
        JsonObject jsonObject = new JsonObject();
        jsonObject.put("username",username);
        jsonObject.put("password",password);
        routingContext.response().headers().set("content-type","application/json; charset=utf-8");
        routingContext.response().end(jsonObject.toString());
    }

}

@Route路由注解,path代表路径,methods代表请求方法
@Route.Routes可以设置多个path请求路径

routingContext.response().end("hello route");响应值
routingContext其它操作具体可以看官方文档 https://vertx.io/docs/vertx-web/java/


还可以不通过注解的方式声明路由,一样可以达到访问效果

public void init(@Observes Router router){
    router.get("/hello-route").handler((routingContext) ->{
        routingContext.response().headers().set("content-type","application/json; charset=utf-8");
        routingContext.response().end("自定义hello route路由");
    });
}

路由拦截器Filters

@ApplicationScoped
public class MyFilter {


    public void filter(@Observes Filters filters){
        filters.register(rc -> {
            String name = rc.request().getParam("name");
            if("xiaobin".equals(name)){
                rc.response().end("xiaobin can not access");
            }else{
                rc.response().putHeader("X-Header", "intercepting the request");
                rc.next();
            }

        }, 100);
    }

}

获取请求的参数name,假如为xiaobin,就直接返回消息,不进行路由转发

你可能感兴趣的:(Quarkus,java)