Java mina GateWayManager 网关管理类

本文介绍了一个用于初始化配置网关并管理其状态的类。通过解析配置字符串,该类创建了一个TCP Socket地址列表。初始化过程中,它会检查配置的有效性并启动扫描器来监控网关状态。如果配置正确,扫描器将开始运行,以确保网络连通性和负载均衡。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值