/** * Generator for Globally unique Strings. */ public class IdGenerator { private static final Logger LOG = LoggerFactory.getLogger(IdGenerator.class); private static final String UNIQUE_STUB; private static int instanceCount; private static String hostName; private String seed; private final AtomicLong sequence = new AtomicLong(1); private int length; static { String stub = ""; boolean canAccessSystemProps = true; try { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertiesAccess(); } } catch (SecurityException se) { canAccessSystemProps = false; } if (canAccessSystemProps) { int idGeneratorPort = 0; ServerSocket ss = null; try { LOG.trace("Using port {}", idGeneratorPort); hostName = InetAddressUtil.getLocalHostName(); ss = new ServerSocket(idGeneratorPort); // -54842-1451457944520- stub = "-" + ss.getLocalPort() + "-" + System.currentTimeMillis() + "-"; Thread.sleep(100); } catch (Exception e) { if (LOG.isTraceEnabled()) { LOG.trace("could not generate unique stub by using DNS and binding to local port", e); } else { LOG.warn("could not generate unique stub by using DNS and binding to local port: {} {}", e.getClass().getCanonicalName(), e.getMessage()); } // Restore interrupted state so higher level code can deal with it. if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } } finally { if (ss != null) { try { // TODO: replace the following line with IOHelper.close(ss) when Java 6 support is dropped ss.close(); } catch (IOException ioe) { if (LOG.isTraceEnabled()) { LOG.trace("Closing the server socket failed", ioe); } else { LOG.warn("Closing the server socket failed" + " due " + ioe.getMessage()); } } } } } // fallback if (hostName == null) { hostName = "localhost"; } hostName = sanitizeHostName(hostName); if (stub.length() == 0) { stub = "-1-" + System.currentTimeMillis() + "-"; } UNIQUE_STUB = stub; } /** * Construct an IdGenerator */ public IdGenerator(String prefix) { synchronized (UNIQUE_STUB) { this.seed = prefix + UNIQUE_STUB + (instanceCount++) + ":"; this.length = this.seed.length() + ("" + Long.MAX_VALUE).length(); } } public IdGenerator() { this("ID:" + hostName); } /** * As we have to find the hostname as a side-affect of generating a unique * stub, we allow it's easy retrieval here * * @return the local host name */ public static String getHostName() { return hostName; } /** * Generate a unique id * * @return a unique id */ public synchronized String generateId() { StringBuilder sb = new StringBuilder(length); sb.append(seed); sb.append(sequence.getAndIncrement()); return sb.toString(); } public static String sanitizeHostName(String hostName) { boolean changed = false; StringBuilder sb = new StringBuilder(); for (char ch : hostName.toCharArray()) { // only include ASCII chars if (ch < 127) { sb.append(ch); } else { changed = true; } } if (changed) { String newHost = sb.toString(); LOG.info("Sanitized hostname from: {} to: {}", hostName, newHost); return newHost; } else { return hostName; } } // public static void main(String[] args) { // IdGenerator generator = new IdGenerator(); // System.out.println(generator.generateId()); // } }
Java 生成唯一的ID
猜你喜欢
转载自zhangyu84849467.iteye.com/blog/2267665
今日推荐
周排行