Vert.x和SpringBoot搭建异步HTTP服务

前言

SpringBoot负责脚手架

Vert.x负责Web服务

Github地址:https://github.com/cklogic/blog/tree/master/vertx-spingboot-demo

运行打开浏览器输入 http://localhost:8888/ 会显示ok,这里使用了dispatcherRoutingContext设计,和SpringMVC一样,可以方便AOP和使用路由表。

实现

        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-web</artifactId>
            <version>3.9.0</version>
        </dependency>
package com.cctv.vertx;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @Title:
 * @BelongProjecet demo
 * @BelongPackage com.example.demo.verticles
 * @Description:
 * @Copyright CCTV.com
 * @Author: lingchuan
 * @Date: 2020-04-08 17:19
 */
@Component
@Slf4j
public class MainVerticle extends AbstractVerticle {

    @Override
    public void start(Future<Void> startFuture) {
        HttpServer server = vertx.createHttpServer();
        Router router = Router.router(vertx);
        router.get("/").handler(this::dispatcherRoutingContext);
        server.requestHandler(router::accept);
        server.listen(8888);
    }

    private void dispatcherRoutingContext(RoutingContext rc) {
        rc.response().setStatusMessage("ok")
                .setStatusCode(200)
                .putHeader("Access-Control-Allow-Credentials", "true")
                .putHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Cookie,Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers")
                .putHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
                .putHeader("Access-Control-Allow-Origin", "*")
                .end("ok");
    }
}
package com.cctv.vertx;

import io.vertx.core.Vertx;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * @Title:
 * @BelongProjecet demo
 * @BelongPackage com.example.demo.runner
 * @Description:
 * @Copyright CCTV.com
 * @Author: lingchuan
 * @Date: 2020-04-08 17:15
 */
@Component
public class WebApplicationRunner implements ApplicationRunner {


    @Autowired
    private MainVerticle mainVerticle;


    @Override
    public void run(ApplicationArguments args) throws Exception {

        Vertx.vertx().deployVerticle(mainVerticle);


    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值