Java mina GateWayScaner Thread

package com.pingan.emall.biz.communication;


import java.io.IOException;
import java.net.SocketAddress;
import java.nio.channels.SocketChannel;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;


/**
 * 網關掃描器, 定時掃描GateWayManager中配置的網關, 更新每個網關的狀態
 * 
 * @author LICHAO844
 *
 */
public class GateWayScaner extends Thread {

private static final Logger LOG = Logger.getLogger(GateWayScaner.class);


private long sleep = 20 * 1000;
private boolean running = true;

private GateWayManager gateWayManager;

public GateWayScaner(GateWayManager gateWayManager) {
this.gateWayManager = gateWayManager;
}
 
public void run() {
while (running) {
//判斷list是否空
if (CollectionUtils.isNotEmpty(gateWayManager.getGateWayList())) {
for (TcpSocketAddress address : gateWayManager.getGateWayList()) {
boolean alive = connectServer(address);
address.setAlive(alive);
if (LOG.isInfoEnabled()) {
LOG.info("Alive state of gate way [" + address + "] is " + alive);
}
}
} else {
LOG.error("No gate way configured");
break;
}

// Only one gate way configured for client, No need to check 
// gate way status for load balance
if (gateWayManager.getGateWaySize() == 1) {
break;
}

try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
LOG.error("Exception happens when sleep for gate way listener", e);
}
}
}

private boolean connectServer(SocketAddress address) {
SocketChannel channel = null;
try {
channel = SocketChannel.open();
channel.configureBlocking(true);
channel.socket().setSoTimeout(20 * 1000);
return channel.connect(address);
} catch (Exception e) {
LOG.error("Failed to connect to gate way [" + address + "]", e);
return false;
} finally {
if (channel != null) {
try {
channel.close();
} catch (IOException e) {
LOG.error("Failed to close socket channel ", e);
}
}
}
}

public void setSleep(long sleep) {
this.sleep = sleep;
}

public void setRunning(boolean running) {
this.running = running;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章