我有一个由vertx创建的UDP服务器。
服务器的目的:它从另一个服务中侦听日志,然后根据消息进行以下操作之一:
1)将消息保存到db
2)根据消息
中的id从db中删除消息3)在db
中更新消息我的代码是:
@AllArgsConstructor
public final class UdpServerVerticle extends AbstractVerticle {
private final Action action;
@Override
public void start() throws Exception {
final DatagramSocket socket = this.vertx.createDatagramSocket(new DatagramSocketOptions());
socket.listen(9000, "0.0.0.0", asyncRes -> {
if (asyncRes.succeeded()) {
socket.handler(packet -> {
final byte[] bytes = packet.data().getBytes(0, packet.data().length());
final String body = this.body(bytes);
this.action.choose(body);
});
} else {
System.out.println("ERROR");
}
});
}
@SneakyThrows
private String body(final byte[] bytes) {
return new String(bytes, "UTF-8");
}
}
动作类:
public final class DefaultAction implements Action {
private final ServerEvent onConnect;
private final ServerEvent onDisconnect;
private final ServerEvent onMatchBegin;
private final ServerEvent onMatchEnd;
@Autowired
public DefaultAction(@EventQualifier(event = EventTypes.CONNECT)final ServerEvent onConnect,
@EventQualifier(event = EventTypes.DISCONNECT)final ServerEvent onDisconnect,
@EventQualifier(event = EventTypes.MATCH_BEGIN)final ServerEvent onMatchBegin,
@EventQualifier(event = EventTypes.MATCH_END)final ServerEvent onMatchEnd) {
this.onConnect = onConnect;
this.onDisconnect = onDisconnect;
this.onMatchBegin = onMatchBegin;
this.onMatchEnd = onMatchEnd;
}
@Override
public void choose(final String body) {
if (this.diconnect(body)) {
this.onDisconnect.make(body);
} else if (this.connect(body)) {
this.onConnect.make(body);
} else if (this.gameBegin(body)) {
this.onMatchBegin.make(body);
} else if (this.gameOver(body)) {
this.onMatchEnd.make(body);
}
}
我非常了解vertx(但我需要使用它)我所知道的是vertx使用单线程来处理我的所有消息。我想将ServerEvent
接口替换为
4个不同的Verticle并使用event bus
将我的消息传递给适当的Verticle,因为它阻止主Verticle线程(UDP服务器)不好。在我的情况下做替换是明智的吗?
答案 0 :(得分:0)
您误解了VertX的工作原理。它是多线程的,但具有线程亲和性,这与单线程不同。
根据你的建议,这是要走的路。将您的每个动作放入一个单独的Verticle中,并使用EventBus与它们进行通信。