网络地址列表工具

来源:互联网 发布:js获取array长度 编辑:程序博客网 时间:2024/06/08 01:07

网络地址列表解析

import static org.apache.zookeeper.common.StringUtils.split;import java.net.InetAddress;import java.net.InetSocketAddress;import java.net.UnknownHostException;import java.util.ArrayList;import java.util.List;import org.apache.commons.lang.StringUtils;/** * 类描述:连接字符串解析器 *  * @author ruipeng.lrp * @since 2017/11/2 **/public final class ConnectStringParser {    private static int defaultPort = 2181;    /**     * 功能:将connectString解析成未解析的InetSocketAddress     *      * @param connectString     * @return InetSocketAddress集合     **/    public static List<InetSocketAddress> parse(String connectString) {        if (StringUtils.isEmpty(connectString)) {            return null;        }        ArrayList<InetSocketAddress> serverAddresses = new ArrayList<InetSocketAddress>();        List<String> hostsList = split(connectString, ",");        for (String host : hostsList) {            int port = defaultPort;            int pidx = host.lastIndexOf(':');            if (pidx >= 0) {                if (pidx < host.length() - 1) {                    port = Integer.parseInt(host.substring(pidx + 1));                }                host = host.substring(0, pidx);            }            serverAddresses.add(InetSocketAddress.createUnresolved(host, port));        }        return serverAddresses;    }    /**     * 功能:将connectString解析成InetSocketAddress     *      * @param connectString     * @return InetSocketAddress集合     **/    public static List<InetSocketAddress> parseAndResolve(String connectString) throws UnknownHostException {        List<InetSocketAddress> serverAddresses = parse(connectString);        List<InetSocketAddress> tmpList = new ArrayList<InetSocketAddress>(serverAddresses.size());        for (InetSocketAddress address : serverAddresses) {            InetAddress ia = address.getAddress();            String addr = (ia != null) ? ia.getHostAddress() : address.getHostString();            InetAddress resolvedAddresses[] = InetAddress.getAllByName(addr);            for (InetAddress resolvedAddress : resolvedAddresses) {                InetAddress taddr = InetAddress.getByAddress(address.getHostString(), resolvedAddress.getAddress());                tmpList.add(new InetSocketAddress(taddr, address.getPort()));            }        }        return tmpList;    }    public static int getDefaultPort() {        return defaultPort;    }    public static void setDefaultPort(int defaultPort) {        ConnectStringParser.defaultPort = defaultPort;    }}

IP列表随机打乱

import java.net.InetSocketAddress;import java.util.Collections;import java.util.LinkedList;import java.util.List;import java.util.Random;import org.apache.commons.collections.CollectionUtils;/** * 类描述:IP列表随机排序工具 *  * @author ruipeng.lrp * @since 2017/11/2 **/public class IPRandomUtils {    /**     * 方式一:利用Collections.shuffle()随机打乱     **/    public static void shuffle(List<InetSocketAddress> serverAddresses) {        if (CollectionUtils.isEmpty(serverAddresses)) {            return;        }        Random sourceOfRandomness = new Random(System.currentTimeMillis() ^ serverAddresses.hashCode());        Collections.shuffle(serverAddresses, sourceOfRandomness);    }    /**     * 方式二:同机房随机打乱,不同机房具有不同优先级     **/    public static void shuffleWithPriority(List<IPWrapper> source) {        if (CollectionUtils.isEmpty(source)) {            return;        }        Collections.sort(source);    }    /**     * 类描述:具有优先级的IP地址,代表不同机房的机器     **/    static class IPWrapper implements Comparable<IPWrapper> {        static Random random = new Random();        String serverIp;        int priority = 0;        int seed;        public IPWrapper(String serverIp) {            try {                this.serverIp = serverIp;                this.seed = random.nextInt(Integer.MAX_VALUE);            } catch (Exception e) {                throw new RuntimeException(e);            }        }        public IPWrapper(String serverIp, int priority) {            try {                this.serverIp = serverIp;                this.priority = priority;                this.seed = random.nextInt(Integer.MAX_VALUE);            } catch (Exception e) {                throw new RuntimeException(e);            }        }        @Override        public int compareTo(IPWrapper other) {            if (priority != other.priority) {                return other.priority - priority;            } else {                return other.seed - seed;            }        }        @Override        public String toString() {            return "IPWrapper [serverIp=" + serverIp + ", priority=" + priority + ", seed=" + seed + "]";        }    }    public static void main(String[] args){        List<IPWrapper> source = new LinkedList<>();        source.add(new IPWrapper("127.0.0.1",0));        source.add(new IPWrapper("234.0.0.1",0));        source.add(new IPWrapper("345.0.0.1",1));        source.add(new IPWrapper("456.0.0.1",2));        IPRandomUtils.shuffleWithPriority(source);        System.out.println(source);    }}

服务器地址列表管理器

import java.util.List;import java.util.concurrent.TimeUnit;import org.apache.commons.collections.CollectionUtils;/** * 功能:服务器地址列表管理器 * 特性1:同机房优先原则(待补充) * 特性2:服务器地址列表定时更新 * 特性3:Round Robin调度策略 **/public class ServerListManagerImpl implements ServerListManager {    private List<ServerListListener> listeners;    private List<String> serverList = null;    private String url;    private int readIndex = -1;    public ServerListManagerImpl(String url){        this.url = url;    }    public void init() throws Exception{        //step1: 初始化服务器地址列表        for (int i = 0; i < 5 && serverList.isEmpty(); ++i) {            serverList = getApacheServerList(url);            if(CollectionUtils.isNotEmpty(serverList)){                return;            }            try {                Thread.sleep((i + 1) * 100L);            } catch (Exception e) {            }        }        //step2: 定时检查服务器地址列表是否更新        TimerService.scheduleWithFixedDelay(new CheckServerListTask(), 0, 3000, TimeUnit.SECONDS);    }    @Override    public String next() {        synchronized(serverList){            if(++readIndex == serverList.size()){                readIndex = 0;            }            return serverList.get(readIndex);        }    }    @Override    public void addListener(ServerListListener listener) {        listeners.add(listener);    }    @Override    public List<String> getApacheServerList(String url) throws Exception {        throw new UnsupportedOperationException();    }    class CheckServerListTask implements Runnable {        @Override        public void run() {            try {                List<String> servers = getApacheServerList(url);                String old = convertList2Str(serverList);                String connectString = convertList2Str(servers);                if(old.equals(connectString)){                    return;                }                synchronized(serverList){                    serverList = servers;                    readIndex = -1;                    for(ServerListListener listener:listeners){                        if(null != listener.getExecutor()){                            listener.getExecutor().execute(()->{listener.serverListChanged(connectString);});                        }else{                            listener.serverListChanged(connectString);                        }                    }                }            } catch (Exception e) {            }        }        String convertList2Str(List<String> list){            StringBuilder sb = new StringBuilder();            for(String ls : list){                sb.append(ls);            }            return sb.toString();        }    }}
原创粉丝点击