前言
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);
}
}