生成唯一UUID

目前有多种方式生成的UUID,根据算法,可确定是否唯一,使用IP和MAC自定义生成唯一主键较妥:

 1  // 获取MAC地址的方法
 2     private static String getMACAddress(InetAddress ia) throws Exception {
 3         // 获得网络接口对象(即网卡),并得到mac地址,mac地址存在于一个byte数组中。
 4         byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
 5         // 下面代码是把mac地址拼装成String
 6         StringBuffer sb = new StringBuffer();
 7         for (int i = 0; i < mac.length; i++) {
 8             if (i != 0) {
 9                 sb.append("-");
10             }
11             // mac[i] & 0xFF 是为了把byte转化为正整数
12             String s = Integer.toHexString(mac[i] & 0xFF);
13             // System.out.println("--------------");
14             // System.err.println(s);
15             sb.append(s.length() == 1 ? 0 + s : s);
16         }
17         // 把字符串所有小写字母改为大写成为正规的mac地址并返回
18         return sb.toString().toUpperCase();
19     }
 1   public static void main(String[] args) throws Exception {
 2             InetAddress ia1 = InetAddress.getLocalHost();// 获取本地IP对象
 3             System.out.println("本机的MAC是 :" + getMACAddress(ia1));
 4             System.out.println("本机的IP是 :" + ia1.getHostAddress());
 5             String uuid = UUID.nameUUIDFromBytes(ia1.getHostAddress().getBytes()).toString();
 6             String uuid1 = UUID.nameUUIDFromBytes(getMACAddress(ia1).getBytes()).toString();
 7             System.out.println(uuid);
 8             System.out.println(uuid1);
 9 
10             }

猜你喜欢

转载自www.cnblogs.com/yln20170705/p/10576792.html