#525 加强Utils Modules模块:网络模块

This commit is contained in:
calvin1978
2017-01-03 22:36:21 +08:00
parent 2adb651507
commit d9d19463e4
5 changed files with 263 additions and 45 deletions
@@ -58,14 +58,15 @@ public class Maps {
* @see org.apache.commons.lang3.concurrent.ConcurrentUtils#createIfAbsent(ConcurrentMap, Object,
* org.apache.commons.lang3.concurrent.ConcurrentInitializer)
*/
public static <K, V> V createIfAbsent(final ConcurrentMap<K, V> map, final K key, final ValueInitializer<V> init) {
if (map == null || init == null) {
public static <K, V> V createIfAbsent(final ConcurrentMap<K, V> map, final K key,
final ValueCreator<? extends V> creator) {
if (map == null || creator == null) {
return null;
}
final V value = map.get(key);
if (value == null) {
return putIfAbsentWithFinalValue(map, key, init.get());
return putIfAbsentWithFinalValue(map, key, creator.get());
}
return value;
}
@@ -155,7 +156,7 @@ public class Maps {
public static <K extends Comparable, V> TreeMap<K, V> newTreeMap() {
return new TreeMap<K, V>();
}
public static <K, V> ConcurrentHashMap<K, V> newConcurrentHashMap() {
return new ConcurrentHashMap<K, V>();
}
@@ -204,11 +205,13 @@ public class Maps {
}
/**
* 创建Value值的回调函数
*
* from Common Lang
*
* @see Maps#createIfAbsent(ConcurrentMap, Object, ValueInitializer)
* @see Maps#createIfAbsent(ConcurrentMap, Object, ValueCreator)
*/
public interface ValueInitializer<T> {
public interface ValueCreator<T> {
/**
* 创建对象
*/
@@ -1,37 +0,0 @@
package org.springside.modules.utils.net;
import java.net.Inet4Address;
import java.net.InetAddress;
import com.google.common.net.InetAddresses;
public class Addresses {
public int toInt(InetAddress address) {
return InetAddresses.coerceToInteger(address);
}
public static String toString(InetAddress ip) {
return InetAddresses.toAddrString(ip);
}
public Inet4Address fromInt(int address) {
return InetAddresses.fromInteger(address);
}
public InetAddress fromString(String address) {
return InetAddresses.forString(address);
}
public static String intToString(int i) {
StringBuilder buf = new StringBuilder(15);
buf.append(i >> 24 & 0xff);
buf.append('.');
buf.append(i >> 16 & 0xff);
buf.append('.');
buf.append(i >> 8 & 0xff);
buf.append('.');
buf.append(i & 0xff);
return buf.toString();
}
}
@@ -0,0 +1,181 @@
package org.springside.modules.utils.net;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.springside.modules.utils.collection.Maps;
import org.springside.modules.utils.collection.Maps.ValueCreator;
import org.springside.modules.utils.text.Strings;
/**
* InetAddress工具类,基于Guava的InetAddress.
*
* 主要包含int, String/IPV4String, InetAdress/Inet4Address之间的互相转转
*
* 先将字符串传换为byte[]再用InetAddress.getByAddress(byte[]),避免了InetAddress.getByName(ip)可能引起的DNS访问.
*
* @author calvin
*/
public class InetAddresses {
private static ConcurrentHashMap<String, InetAddress> strToInetCache = Maps.newConcurrentHashMap();
private static ConcurrentHashMap<Integer, Inet4Address> intToInetCache = Maps.newConcurrentHashMap();
/**
* 从InetAddress转化到int, 传输和存储时, 用int代表InetAddress是最小的开销.
*
* InetAddress可以是IPV4或IPV6,都会转成IPV4.
*
* @see com.google.common.net.InetAddresses#coerceToInteger(InetAddress)
*/
public int toInt(InetAddress address) {
return com.google.common.net.InetAddresses.coerceToInteger(address);
}
/**
* InetAddress转换为String.
*
* InetAddress可以是IPV4或IPV6. 其中IPV4直接调用getHostAddress()
*
* @see com.google.common.net.InetAddresses#toAddrString(InetAddress)
*/
public static String toString(InetAddress ip) {
return com.google.common.net.InetAddresses.toAddrString(ip);
}
/**
* 从int转换为Inet4Address(仅支持IPV4)
*/
public Inet4Address fromInt(int address) {
return com.google.common.net.InetAddresses.fromInteger(address);
}
/**
* 从int转换为Inet4Address(仅支持IPV4)
*
* 如果应用中需要处理的InetAddress非常有限,使用又非常频繁时,可使用本方法。
*/
public Inet4Address fromIntInCache(final int address) {
return Maps.createIfAbsent(intToInetCache, address, new ValueCreator<Inet4Address>() {
public Inet4Address get() {
return com.google.common.net.InetAddresses.fromInteger(address);
}
});
}
/**
* 从String转换为InetAddress.
*
* IpString可以是ipv4 或 ipv6 string, 但不可以是域名.
*
* 先字符串传换为byte[]再调getByAddress(byte[]),避免了调用getByName(ip)可能引起的DNS访问.
*/
public InetAddress fromIpString(String address) {
return com.google.common.net.InetAddresses.forString(address);
}
/**
* 从String转换为InetAddress.
*
* IpString可以是ipv4 或 ipv6 string, 但不可以是域名.
*
* 先字符串传换为byte[]再用getByAddress(byte[]),避免了getByName(name)可能引起的DNS访问.
*/
public InetAddress fromIpStringInCache(final String address) {
return Maps.createIfAbsent(strToInetCache, address, new ValueCreator<InetAddress>() {
public InetAddress get() {
return com.google.common.net.InetAddresses.forString(address);
}
});
}
/**
* 从IPv4String转换为InetAddress.
*
* IpString如果确定ipv4, 使用本方法减少字符分析消耗 .
*
* 先字符串传换为byte[]再调getByAddress(byte[]),避免了调用getByName(ip)可能引起的DNS访问.
*/
public Inet4Address fromIp4String(String address) {
byte[] bytes = ip4StringToBytes(address);
if (bytes == null) {
return null;
} else {
try {
return (Inet4Address) Inet4Address.getByAddress(bytes);
} catch (UnknownHostException e) {
throw new AssertionError(e);
}
}
}
/**
* 从IPv4String转换为InetAddress.
*
* IpString如果确定ipv4, 使用本方法减少字符分析消耗 .
*
* 先字符串传换为byte[]再用InetAddress.getByAddress(byte[]),避免了InetAddress.getByName(ip)可能引起的DNS访问.
*/
public Inet4Address fromIp4StringInCache(final String address) {
return (Inet4Address) Maps.createIfAbsent(strToInetCache, address, new ValueCreator<Inet4Address>() {
public Inet4Address get() {
return fromIp4String(address);
}
});
}
/**
* int转换到IPV4 String
*/
public static String intToIpv4String(int i) {
StringBuilder buf = new StringBuilder(15);
buf.append(i >> 24 & 0xff);
buf.append('.');
buf.append(i >> 16 & 0xff);
buf.append('.');
buf.append(i >> 8 & 0xff);
buf.append('.');
buf.append(i & 0xff);
return buf.toString();
}
/**
* Ipv4 String 转换到int
*/
public static int Ipv4StringToInt(String ipv4Str) {
byte[] byteAddress = ip4StringToBytes(ipv4Str);
if (byteAddress == null) {
return 0;
} else {
return ((byteAddress[0] & 0xff) << 24) | ((byteAddress[1] & 0xff) << 16) | ((byteAddress[2] & 0xff) << 8)
| (byteAddress[3] & 0xff);
}
}
/**
* Ipv4 String 转换到byte[]
*/
private static byte[] ip4StringToBytes(String ipv4Str) {
if (ipv4Str == null) {
return null;
}
List<String> it = Strings.split(ipv4Str, '.', 4);
if (it.size() != 4) {
return null;
}
byte[] byteAddress = new byte[4];
for (int i = 0; i < 4; i++) {
int tempInt = Integer.parseInt(it.get(i));
if (tempInt > 255) {
return null;
}
byteAddress[i] = (byte) tempInt;
}
return byteAddress;
}
}
@@ -0,0 +1,71 @@
package org.springside.modules.utils.net;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.util.Random;
import javax.net.ServerSocketFactory;
public class Nets {
public static final int PORT_RANGE_MIN = 1024;
public static final int PORT_RANGE_MAX = 65535;
private static final Random random = new Random();
/**
* 测试端口是否空闲可用, from Spring SocketUtils
*/
public static boolean isPortAvailable(int port) {
try {
ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(port, 1,
InetAddress.getByName("localhost"));
serverSocket.close();
return true;
} catch (Exception ex) {
return false;
}
}
/**
* 随机找一个空闲端口,from Spring SocketUtils
*/
public static int findRandomAvailablePort() {
return findRandomAvailablePort(PORT_RANGE_MIN, PORT_RANGE_MAX);
}
/**
* 在一个范围里随机找一个空闲端口,from Spring SocketUtils
*/
public static int findRandomAvailablePort(int minPort, int maxPort) {
int portRange = maxPort - minPort;
int candidatePort;
int searchCounter = 0;
do {
if (++searchCounter > portRange) {
throw new IllegalStateException(
String.format("Could not find an available tcp port in the range [%d, %d] after %d attempts",
minPort, maxPort, searchCounter));
}
candidatePort = minPort + random.nextInt(portRange + 1);
} while (!isPortAvailable(candidatePort));
return candidatePort;
}
/**
* 从某个端口开始,递增找一个空闲端口.
*/
public static int findAvailablePortFrom(int minPort) {
for (int port = minPort; port < PORT_RANGE_MAX; minPort++) {
if (isPortAvailable(port)) {
return port;
}
}
throw new IllegalStateException(
String.format("Could not find an available tcp port in the range [%d, %d]", minPort, PORT_RANGE_MAX));
}
}
@@ -4,7 +4,7 @@ import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentMap;
import org.springside.modules.utils.collection.Maps;
import org.springside.modules.utils.collection.Maps.ValueInitializer;
import org.springside.modules.utils.collection.Maps.ValueCreator;
import net.sf.cglib.reflect.FastClass;
import net.sf.cglib.reflect.FastMethod;
@@ -24,7 +24,7 @@ public class FastMethodInvoker {
public static FastMethod getFastMethod(final Object obj, final String methodName, Class<?>... parameterTypes) {
final Class<?> clz = obj.getClass();
FastClass fastClz = Maps.createIfAbsent(classMap, clz, new ValueInitializer<FastClass>() {
FastClass fastClz = Maps.createIfAbsent(classMap, clz, new ValueCreator<FastClass>() {
@Override
public FastClass get() {
return FastClass.create(clz);