Java mina GateWayManager 網關管理類

package com.pingan.emall.biz.communication;


import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;


/**
 * 網關管理類, 初始化配置的網關, 並管理網關狀態。
 * @author LICHAO844
 *
 */
public class GateWayManager {


private static Logger LOG = Logger.getLogger(GateWayManager.class);


private List<TcpSocketAddress> gateWayList = new ArrayList<TcpSocketAddress>();
private AtomicLong invokeCount = new AtomicLong(0);
private GateWayScaner scaner;

public GateWayManager(String gateWays) {
String[] gateWayArray = StringUtils.split(gateWays, '|');


for (String gateWay : gateWayArray) {
String[] ipPortArray = StringUtils.split(gateWay, ':');
if (ipPortArray.length == 2) {
String ip = ipPortArray[0];
int port = Integer.parseInt(ipPortArray[1]);
gateWayList.add(new TcpSocketAddress(ip, port));
} else {
LOG.error("Invalid gate way configuration " + gateWay);
}
}

if (getGateWaySize() == 0) {
LOG.error("No correct gate way configured");
} else {
scaner = new GateWayScaner(this);
scaner.start();
}
}


protected int getGateWaySize() {
return gateWayList.size();
}


protected List<TcpSocketAddress> getGateWayList() {
return gateWayList;
}

/**
* 隨機返回一個當前存活的網關
* @return
*/
public SocketAddress getRandomGateWay() {
if (CollectionUtils.isEmpty(gateWayList)) {
return null;
}

ArrayList<SocketAddress> tempList = new ArrayList<SocketAddress>(gateWayList.size());
for (TcpSocketAddress address : gateWayList) {
if (address.isAlive()) {
tempList.add(address);
}
}


if (tempList.size() == 0) {
LOG.error("No gate way is alive");
return null;
}


if (tempList.size() == 1) { 
return tempList.get(0);
} else {
int i = (int) (invokeCount.incrementAndGet() % tempList.size());
return tempList.get(i);
}
}

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