简体   繁体   English

Netty-TCP-HTTP-MQTT设计

[英]Netty-TCP-HTTP-MQTT design

I am trying to write a server-side java application that can accept tcp, http and mqtt communication (receive and send/ MongoDB as storage). 我正在尝试编写一个服务器端Java应用程序,它可以接受tcp,http和mqtt通信(接收和发送/ MongoDB作为存储)。 From research, we decided that it could be a jar application based on Netty and paho for mqtt. 通过研究,我们认为它可能是基于Netty和paho的mqtt的jar应用程序。 We have 3 project using three of these protocols, therefore I am trying to unify the connection module. 我们有3个项目使用其中的三种协议,因此我试图统一连接模块。 They each have different protocol style, for example: 它们各自具有不同的协议样式,例如:

-tcp: 0102330123456700 -tcp:0102330123456700

-http: HTTP POST /URL/count {"id":"02","count":"01234567"} -http:HTTP POST / URL / count {“ id”:“ 02”,“ count”:“ 01234567”}

-mqtt: topic /02/count {"count":"01234567"} -mqtt:主题/ 02 / count {“ count”:“ 01234567”}

Since we are a bit short of time, i am running them three in a silly but quick way---3 different thread listening to 3 different ports. 由于我们时间不够,我以一种愚蠢但快速的方式运行它们三个--3个不同的线程侦听3个不同的端口。

public class ServerLauncher {
public static void main(String[] args) {
    NettyRestServer nettyRestServer = new NettyRestServer();
    MqttServer mqttServer = new MqttServer();
    EchoServer echoServer =  new EchoServer();

    new Thread(nettyRestServer,"HTTP Listening").start();
    new Thread(mqttServer,"Mqtt Listening").start();
    new Thread(echoServer,"socket Listening").start();
}

} }

My questions are: 我的问题是:

  1. Since they are all based on tcp, is there a good way to manage them all together without wasting thread resource? 由于它们都是基于tcp的,是否有一种很好的方法可以一起管理它们而不浪费线程资源? maybe running just one thread for listening one port. 也许只运行一个线程来监听一个端口。 I only find examples of single protocol. 我只找到单一协议的示例。
  2. For data storage, is it an okey design to push all the incoming messages to a concurrentHashMap across all thread/channels. 对于数据存储,将所有传入的消息跨所有线程/通道推送到并发HashMap是一项明智的设计。 Finally with a another thread running scheduled task, storage this concurrentHashMap into MongoDB and reset. 最后,通过另一个运行计划任务的线程,将此并发哈希表存储到MongoDB中并重置。 or maybe use queue instead of concurrentHashMap 或者也许使用队列而不是并发HashMap

如果将Netty用于所有这些,则可以为所有服务器共享相同的EventLoopGroup ,这意味着所有服务器都将共享相同的Threads

You don't have to use three threads to start Server. 您不必使用三个线程来启动Server。 You can do all of these in only one ServerBootstrap. 您只能在一个ServerBootstrap中完成所有这些操作。 And put the logic in ChannelHandler. 并将逻辑放在ChannelHandler中。

Netty's ChannelPipeline can dynamicly change ChannelHandler when getting the connecttion. Netty的ChannelPipeline在获得连接时可以动态更改ChannelHandler。

  ctx.pipeline().addBefore(...)
  ctx.pipeline().addAfter(...)
  ctx.pipeline().remove(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM