http://yangshangchuan.iteye.com/blog/2012401
首先,定义了一个统一的接口,以支持不同操作系统不同实现的透明切换:
Java代码 收藏代码
/**
*生成机器码的接口,不同平台有不同实现
* @author 杨尚川
*/
public interface SequenceService {
/**
* 获取机器码
* @return 机器码
*/
public String getSequence();
}
其次,定义了一个抽象类,实现了一些通用的功能,如生成MD5摘要、将很长的字符串以固定的位数分割开,以便于人类阅读(如将机器码 71F5DA7F495E7F706D47F3E63DC6349A 每4个一组,以-分割为71F5-DA7F-495E-7F70-6D47-F3E6-3DC6-349A)、利用sigar来生成机器码。这里需要在pom.xml中加入sigar依赖。
Xml代码 收藏代码
org.fusesource
sigar
1.6.4
log4j
log4j
Java代码 收藏代码
import org.apdplat.module.system.service.PropertyHolder;
import org.apdplat.platform.log.APDPlatLogger;
import org.apdplat.platform.util.ConvertUtils;
import org.apdplat.platform.util.FileUtils;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import org.apdplat.platform.log.APDPlatLoggerFactory;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.NetFlags;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.Sigar;
/**
*机器码生成的通用服务
* @author 杨尚川
*/
public abstract class AbstractSequenceService implements SequenceService{
protected final APDPlatLogger LOG = APDPlatLoggerFactory.getAPDPlatLogger(getClass());
/**
* 对一段String生成MD5摘要信息
* @param message 要摘要的String
* @return 生成的MD5摘要信息
*/
protected String getMD5(String message) {
message += "{apdplat}";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
LOG.debug("MD5摘要长度:" + md.getDigestLength());
byte[] b = md.digest(message.getBytes("utf-8"));
String md5 = ConvertUtils.byte2HexString(b)+message.length();
return getSplitString(md5);
} catch (NoSuch