其他分享
首页 > 其他分享> > vert.x3 EventBus sockjs消息推送

vert.x3 EventBus sockjs消息推送

作者:互联网

pom.xml
<dependency>
    <groupId>io.vertx</groupId>
    <artifactId>vertx-core</artifactId>
    <version>3.7.0</version>
</dependency>
<dependency>
    <groupId>io.vertx</groupId>
    <artifactId>vertx-web</artifactId>
    <version>3.7.0</version>
</dependency>
AppVerticle.java
package com.zenith.microservices.demo.verticle;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.logging.Logger;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.StaticHandler;
import io.vertx.ext.web.handler.sockjs.BridgeOptions;
import io.vertx.ext.web.handler.sockjs.PermittedOptions;
import io.vertx.ext.web.handler.sockjs.SockJSHandler;

import java.util.Date;

public class AppVerticle extends AbstractVerticle {

  public static void main(String[] args){
    Vertx vertx = Vertx.vertx();
    //发布服务
    vertx.deployVerticle(AppVerticle.class.getName());
  }

  @Override
  public void start() throws Exception {
    //创建路由器
    final Router router = Router.router(vertx);
    router.route().handler(BodyHandler.create());

    final BridgeOptions options = new BridgeOptions()
            .addInboundPermitted(new PermittedOptions().setAddress("to_publish"))//注册服务器地址
            .addOutboundPermitted(new PermittedOptions().setAddress("to_client"));//注册客户端地址

    final SockJSHandler ebHandler = SockJSHandler.create(vertx).bridge(options);
    //请求路由
    router.route("/eventbus/*").handler(ebHandler);

   //定时向前端发送消息(1s)
    vertx.setPeriodic(1000 , timerID -> {
      vertx.eventBus().publish("to_client", "现在时间是:"+new Date());//发布消息
    });
	//静态资源,在resource目录下新建webroot目录,再新建index.html
    router.route().handler(StaticHandler.create());
	//创建服务器并监听8080端口
    vertx.createHttpServer().requestHandler(router::accept) .listen(8080);
  }
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>SockJS/EB</title>
</head>
<body>
<div id="data">
</div>
</body>
<!-- 页面引入-->
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="/sockjs.min.js"></script>
<script type="text/javascript" src="/vertx-eventbus.js"></script>
<script type="text/javascript">
   //获取EventBus对象
    eb = new EventBus('/eventbus/');
    eb.onopen = function () {
        //通过注册过的客户端名称,回调获取数据
        eb.registerHandler('to_client', function (err,msg) {
        	//获取服务器发送的数据
            $('#data').prepend('<div>' + msg.body + '</div>');
        });
    }
</script>
</html>
目录结构

vertx-eventbus-sockjs消息推送

标签:web,sockjs,vert,router,handler,io,import,x3,vertx
来源: https://blog.csdn.net/qq_33293878/article/details/89539076