Vertx的netty事件循环仅使用一个线程

问题描述

似乎一个顶点只能由单个线程执行,并且总是由同一线程执行。 但是Vert.x能够通过在每个cpu中创建一个线程来使用计算机中的所有cpu。 每个线程可以将消息发送到多个顶点。

但是,在性能测试期间在标准verticle上对vertx http服务器进行性能分析时,我只能看到1个线程处理所有处理(vert.x-eventloop-thread-0)。

如何使所有8个事件循环线程都处理到垂直消息的消息?

CountDownLatch latch = new CountDownLatch(1);
final List<Throwable> errors = new ArrayList<>();

local = new Local(getVertx(),settings,options,connectionHandler,exceptionHandler);

LocalVerticle.vertxDeployMap.put(local.hashCode(),local);

DeploymentOptions dop = new DeploymentOptions()
        .setInstances(new VertxOptions()
        .getEventLoopPoolSize())
        .setConfig(new JsonObject().put("local",local.hashCode()));

Network.getVertx().deployVerticle(LocalVerticle.class.getName(),dop,(event) -> {
    if (!event.Failed()) {
        latch.countDown();
    } else {
        errors.add(event.cause());
    }
});

boolean await = latch.await(10,TimeUnit.SECONDS);
if (!await) {
    if (errors.isEmpty()) {
        throw new Exception("Failed to initialize Local Verticle");
    } else {
        throw new Exception("Failed to initialize Local Verticle",errors.get(0));
    }
}

LocalVerticle.vertxDeployMap.remove(local.hashCode());


public class LocalVerticle extends AbstractVerticle {

    static final Map<Integer,Local> vertxDeployMap = new HashMap<>();
    
    private HttpServer httpServer;

    @Override
    public void start() throws Exception {
        
        Local local = vertxDeployMap.get(this.config().getInteger("local"));

        HttpServerOptions options = local.getoptions();
        Handler<httpconnection> connectionHandler = local.getConnectionHandler();
        Handler<Throwable> exceptionHandler = local.getExceptionHandler();
        Router router = local.getRouter();

        this.httpServer = this.vertx
                .createHttpServer(options)
                .exceptionHandler(exceptionHandler)
                .connectionHandler(connectionHandler)
                .requestHandler(router)
                .listen();

    }

    @Override
    public void stop() throws Exception {
        if (this.httpServer != null) {
            this.httpServer.close();
            this.httpServer = null;
        }
    }
}

解决方法

设计Vert.x线程模型是为了使已部署Verticle的特定实例始终锁定在单个线程上。为了跨内核扩展您的应用程序,您需要deploy multiple instances of your Verticle

使用顶点名称部署顶点时,可以指定要部署的顶点实例数:

DeploymentOptions options = new DeploymentOptions().setInstances(16);
vertx.deployVerticle("com.mycompany.MyOrderProcessorVerticle",options);

这对于轻松跨多个内核进行扩展很有用。例如,您可能有一个要部署的Web服务器版本,并且在您的计算机上有多个核心,因此您想要部署多个实例以利用所有核心。