close
# Using the algorithm from Hibernate to generate UUID require 'socket' require 'thread' class UUID @@instance = nil @@mutex = Mutex.new def initialize @IP = 0 ipStr = IPSocket.getaddress(Socket.gethostname) ipStr.split('.').collect {|a| a.to_i}.pack('C*').each_byte {|a| @IP = (@IP << 8) - 128 + a} @counter = -1 @JVM = (currentTimeMillis >> 8) & 0xffffffff end def currentTimeMillis (Time.new.to_f * 1000).to_i end def getJVM @JVM end def getCount @@mutex.synchronize do @counter = (@counter + 1) % 32768 end end def getIP @IP end def getHiTime currentTimeMillis >> 32 end def getLoTime currentTimeMillis & 0xffffffff end def generate sprintf(’%08x-%08x-%04x-%08x-%04x’, getIP, getJVM, getHiTime, getLoTime, getCount) end def UUID.getInstance @@mutex.synchronize do @@instance = new unless @@instance end @@instance end def UUID.getUUID getInstance.generate end end
全站熱搜