gpt4 book ai didi

java - Netty - sendAsync()组空指针异常

转载 作者:行者123 更新时间:2023-11-30 02:00:42 26 4
gpt4 key购买 nike

我正在尝试使用 Atomix 在 Java 的两个进程之间发送消息和 Netty 。我有一个名为 Starter 的程序,它负责向所有正在等待该消息的正在运行的进程发送消息。

这是入门版:

Address[] network = {
Address.from("localhost:23450"),
Address.from("localhost:23451"),
Address.from("localhost:23452"),
Address.from("localhost:23453")
};

Serializer s = new SerializerBuilder().build();

ExecutorService es = Executors.newSingleThreadExecutor();

ManagedMessagingService ms = NettyMessagingService.builder()
.withAddress(Address.from("localhost:23459"))
.build();

ms.registerHandler("start", (o,m)->{
System.out.println("Hello "+s.decode(m)+" from "+o);
}, es);

ms.sendAsync(Address.from("localhost:23459"), "start", s.encode("start"));

for (int i = 0; i < network.length; i++) {
ms.sendAsync(network[i], "start", s.encode("start"));
}

这是过程:

Address[] network = {
Address.from("localhost:23450"),
Address.from("localhost:23451"),
Address.from("localhost:23452"),
Address.from("localhost:23453")
};

int id = Integer.parseInt(args[0]);

Serializer s = new SerializerBuilder().addType(Msg.class).build();

ManagedMessagingService ms = NettyMessagingService.builder()
.withAddress(network[id])
.build();

ExecutorService es = Executors.newSingleThreadExecutor();
ExecutorService es2 = Executors.newSingleThreadExecutor();

ms.registerHandler("leader", (o,m) -> {
int i = s.decode(m);

if(leader < i){
leader = i;
System.out.println("Leader updated to: " + i);
}
else{
System.out.println("Received: " + i + ". Not updated.");
}
}, es);

ms.registerHandler("start", (o,m) -> {
for(int i=0; i < network.length ; i++ ){
ms.sendAsync(network[i],"leader", s.encode(id));
}
System.out.println("Started");
},es2);

每个正在运行的进程都有一个 ID(作为参数传递)。地址是已知的。

我有两个问题。

第一个是应该等待的进程正在终止。

第二个,Starter 无法向其他进程发送消息。我得到:

Exception in thread "main" java.lang.NullPointerException: group

我做错了什么?应该改变解决问题的方法吗?

最佳答案

我解决了在两个文件中添加 ms.start(); 的问题。最终结果为:

ManagedMessagingService ms = NettyMessagingService.builder()
.withAddress(network[id])
.build();

//(...)
ms.start();

ms.registerHandler("leader", (o,m) -> {
//...
});

关于java - Netty - sendAsync()组空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52934697/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com