バーク:
私は、ホストがJavaでエグゼキュータを使用して生きているのか死んでいることを認識しようとしています。私の場合、私はリストに保持severealホストを持っています。
私の目標は、ホストの数と、それらをチェックしてスレッドを作成することです。スレッドが近いホスト、ホストdoesntの接続、及びcontiniously例えば50(DEAD)又は51(生きている)状況コードを送信して接続したとき。
私の問題は、スレッドが唯一のホストに接続することができます。例えば;
私は2つのホスト192.168.1.1と192.168.1.2を持っています。スレッドは、バックグラウンドでそれらの両方をチェックする必要がありますが、私はわずか1.1に接続することができます
接続
List <Host> hosts = LoadBalancer.getHostList();
ExecutorService executor = Executors.newFixedThreadPool(hosts.size());
executor.submit(()->{
for (Host host:hosts) {
try {
connect(host,"message",1);
} catch (Exception e) {
e.printStackTrace();
}
}
});
また、私はHOST.javaののsetActive関数の内部をsyncronizedています
HOST.JAVA
public class Host {
private String ip;
private int port;
private boolean isActive;
public Host(String ip, int port) {
this.ip = ip;
this.port = port;
this.isActive = true;
}
public synchronized boolean isActive() {
return isActive;
}
public synchronized void setActive(boolean active) {
isActive = active;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
接続機能
public static void connect(Host host, String message, int mode) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap clientBootstrap = new Bootstrap();
clientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 500);
clientBootstrap.group(group);
clientBootstrap.channel(NioSocketChannel.class);
clientBootstrap.remoteAddress(new InetSocketAddress(host.getIp(), host.getPort()));
clientBootstrap.handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel socketChannel) {
//TODO, TIMEOUT BILGISI ILE DOLDUR BURAYI
//socketChannel.pipeline().addLast(new ReadTimeoutHandler(1));
//socketChannel.pipeline().addLast("idleStateHandler", new IdleStateHandler(1, 1, 2));
socketChannel.pipeline().addLast(new ClientHandler(host, message, mode));
}
});
ChannelFuture channelFuture = clientBootstrap.connect().sync();
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
System.err.println("Connection timed out --> " + e);
host.setActive(false); //connection kurulamadı demektir. Bir sonraki mesaj geldiğinde bu hostun açılıp açılmadığı denenecek.
} finally {
group.shutdownGracefully().sync();
}
}
料理:
この:
executor.submit(()->{
for (Host host:hosts) {
try {
connect(host,"message",1);
} catch (Exception e) {
e.printStackTrace();
}
}
});
シングルスレッドでに接続されているすべてのホストでの結果。あなたはそれのようなものを読みたいです
for (Host host: hosts) {
executor.submit(()->{
try {
connect(host,"message",1);
} catch (Exception e) {
e.printStackTrace();
}
}
});