【发布时间】:2015-03-07 09:50:54
【问题描述】:
对于当前的项目,我需要以一种有效的方式实现自定义但预定义的网络协议,因为该软件将在不是很小的多用户环境中运行。重要的是,协议处理本身非常快,而且开销很小,因此 CPU 和其他硬件可以完全用于服务器本身的工作。
我知道已经有关于类似事情的问题,但我认为我的问题有些不同。
让我向您展示我目前使用的两种不同的方法:
方法 1
public class CommandRegistry {
private HashMap<String, HashSet<CommandExecutor>> mainHandlers = new HashMap<>();
public void registerMainHandler(CommandExecutor executor, String command) {
if (mainHandlers.get(command) == null) {
HashSet<CommandExecutor> executors = new HashSet<>();
executors.add(executor);
mainHandlers.put(command, executors);
} else {
HashSet<CommandExecutor> executors = mainHandlers.get(command);
executors.add(executor);
mainHandlers.remove(command);
mainHandlers.put(command, executors);
}
}
public void executeCommand(String command) {
for (CommandExecutor executor : mainHandlers.get(command)) {
executor.call();
}
}
}
CommandExecutor 类在这里是抽象的,当然还有实现协议命令的子类。
在这种方法中,命令注册表从一开始就已经知道哪个执行器用于协议的哪个部分,所以我认为它不是很动态,但我想它足以满足我的需求。
方法 2
public class CommandRegistry {
private List<CommandExecutor> executors = new ArrayList<>();
public void registerCommand(CommandExecutor executor) {
this.executors.add(executor);
}
public void callCommand(String command) {
for (CommandExecutor exec : executors) {
exec.callCommand(command);
}
}
}
public abstract class CommandExecutor {
List<String> myCommands;
public CommandExecutor(String... commands) {
this.myCommands = commands.toArray();
}
public void callCommand(String command) {
if (this.myCommands.contains(command)) {
this.executeCommandProcedure();
}
}
// This method contains the actual command procedure
protected abstract void executeCommandProcedure();
}
在这种方法中,只有CommandExecutor 自己知道它是否要处理命令。在调用命令时,我们将遍历所有已注册的处理程序并调用那些可能效率低下的方法,我认为。
知道,我的问题是,您认为哪种设计更好。请在回答时考虑设计和性能,因为两者对我来说都非常重要。
也许您甚至可以推荐一个更好的设计(也更有效)?
// 编辑:
在重新考虑了设计之后,我开始寻找另一种方法,基于我想用于网络的外部库“Netty”。
我以为我为要处理的协议的每个部分编写了ChannelInboundHandlerAdapter 类,并将它们添加到 Netty 管道中。这对 Netty 来说效率高还是成本太高?
【问题讨论】:
-
您打算同时处理多少请求?
-
我猜大概有几百个。问题是协议“说话”非常多,所以不仅有
Connect -> some data -> disconnect,而且客户端和服务器之间有很多通信。
标签: java performance network-programming netty