vertx 内的多线程 [英] multithreading within vertx

查看:77
本文介绍了vertx 内的多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 vert.x 的新手.我正在尝试 vert.xNetServer"功能.http://vertx.io/core_manual_java.html#writing-tcp-servers-and-clients 和它的作用就像一个魅力.

I am a newbie to vert.x. I was trying out the vert.x "NetServer" capability. http://vertx.io/core_manual_java.html#writing-tcp-servers-and-clients and it works like a charm .

但是,我也读到垂直实例是严格单线程的.

However , I also read that "A verticle instance is strictly single threaded.

如果您创建一个简单的 TCP 服务器并部署它的单个实例,那么该服务器的所有处理程序总是在同一个事件循环(线程)上执行."

If you create a simple TCP server and deploy a single instance of it then all the handlers for that server are always executed on the same event loop (thread)."

目前,对于我的实现,我想接收 TCP 字节流,然后触发另一个组件.但这不应该是 Verticle 的start"方法中的阻塞调用.那么,在 start 方法中编写一个 executor 是一个好习惯吗?或者 vertx 会自动处理这种情况.

Currently, for my implementation, I wanted to receive the TCP stream of bytes and then trigger another component. But this should not be a blocking call within the "start" method of the Verticle. So, is it a good practice, to write an executor within the start method? or does vertx automatically handle such cases.

这是一个片段

public class TCPListener extends Verticle {

    public void start(){

        NetServer server = vertx.createNetServer();

        server.connectHandler(new Handler<NetSocket>() {
            public void handle(NetSocket sock) {
                container.logger().info("A client has connected");
                sock.dataHandler(new Handler<Buffer>() {
                    public void handle(Buffer buffer) {
                        container.logger().info("I received " + buffer.length() + " bytes of data");

                        container.logger().info("I received " + new String(buffer.getBytes()));
                        //Trigger another component here. SHould be done in a sperate thread. 
                        //The previous call should be returned . No need to wait for component response.
                    }
                });
            }
        }).listen(1234, "host");
    }
}

应该是什么机制才能使其成为非阻塞调用.

What should be mechanism to make this a non blocking call.

推荐答案

我不认为这是 vert.x 的方式.

I don't think this is the way to go for vert.x.

更好的方法是正确使用事件总线而不是 Executor.让工作人员响应总线上的事件,进行处理,并在完成时向总线发出信号.

A better way would be to use the event bus properly instead of Executor. Have a worker respond to the event on the bus, do the processing, and signal the bus when it's completed.

创建线程违背了使用 vert.x 的目的.

Creating threads defeats the purpose of going with vert.x.

这篇关于vertx 内的多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆