/** * * @Title: DistributedIdGenerator.java * @Description: Distributed id generator (10-digit timestamp (seconds) + self-incrementing id + 2-digit machine id) can be guaranteed to be unique in the cluster (the number of serverNums machines must be configured) * @date August 10, 2016 * @version V1.0 */ public class DistributedIdGenerator { static String SERVER_ID_PREFIX=getServerId(); static final String EMPTY=""; final Map<Integer,Integer> secondSequenceMap=new ConcurrentHashMap<Integer, Integer>(); public DistributedIdGenerator(int serverNums){ } public DistributedIdGenerator(){ } public synchronized long generateId(){ long time = System.currentTimeMillis(); int second=(int) (time/1000L); int sequence=0; if(secondSequenceMap.containsKey(second)){ sequence=secondSequenceMap.get(second); }else{ secondSequenceMap.clear(); } sequence++; secondSequenceMap.put(second, sequence); return Long.valueOf(second+EMPTY+sequence+SERVER_ID_PREFIX); } /** * There is still a chance that the pid will be repeated (although random numbers are added) * @return */ private static String getServerId(){ String name = ManagementFactory.getRuntimeMXBean().getName(); String pid = name.split("@")[0]; int random=new Random().nextInt(10); if(pid.length()<=1){ pid=pid+""+random; } if(pid.length()>2){ pid=pid.substring(0, 2); } if(random==0){ random=1; } return random+pid; } public static void main(String[] args) throws Exception { final Map<Long,Long> sets = new ConcurrentHashMap<Long,Long>(); final AtomicInteger counts = new AtomicInteger(0); final DistributedIdGenerator idGen = new DistributedIdGenerator(1); List<Callable<Long>> partitions = new ArrayList<Callable<Long>>(); for (int i = 0; i < 100; i++) { partitions.add(new Callable<Long>() { @Override public Long call() throws Exception { for(int j=0;j<10000;j++){ long id = idGen.generateId(); System.out.println(id); if (sets.containsKey(id) ){ counts.incrementAndGet(); } sets.put(id, id); } return 0l; } }); } ExecutorService executorPool = Executors.newFixedThreadPool(Runtime .getRuntime().availableProcessors()*4); try { long s = System.currentTimeMillis(); executorPool.invokeAll(partitions); long s_avg = System.currentTimeMillis() - s; System.out.println("Completion time required: " + s_avg / 1.0e3 + "seconds"); executorPool.shutdown(); } catch (Exception e) { e.printStackTrace (); } System.out.println("Number of repetitions: "+counts.get()); long time = System.currentTimeMillis(); int second=(int) (time/1000L); System.out.println(second); } }
distributed id generator, internet
A simple distributed id generator, 10-digit timestamp (seconds) + self-incrementing id + 2-digit machine id, should be able to meet general applications; original, please indicate the source when reprinting
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=326942391&siteId=291194637
Ranking