項目在設計表的時候,要處理并發多的一些資料,類似訂單号不能重複,要保持唯一。原本以為來個時間戳,精确到毫秒應該不錯了。後來覺得是錯了,測試環境下很多一樣的id,不能達到唯一辨別。
jdk api 是這麼說的:
“表示通用唯一辨別符 (uuid) 的類。 uuid 表示一個 128 位的值。”
詳細的說就是:
“uuid
含義是通用唯一識别碼 (universally unique identifier),這 是一個軟體建構的标準,也是被開源軟體基金會 (open
software foundation, osf) 的組織在分布式計算環境 (distributed computing
environment, dce) 領域的一部份。uuid
的目的,是讓分布式系統中的所有元素,都能有唯一的辨識資訊,而不需要透過中央控制端來做辨識資訊的指定。如此一來,每個人都可以建立不與其它人沖突的
uuid。在這樣的情況下,就不需考慮資料庫建立時的名稱重複問題。目前最廣泛應用的 uuid,即是微軟的 microsoft’s globally
unique identifiers (guids),而其他重要的應用,則有 linux ext2/ext3 檔案系統、luks
加密分割區、gnome、kde、mac os x 等等。”
uuid由以下幾部分的組合:
(1)目前日期和時間,uuid的第一個部分與時間有關,如果你在生成一個uuid之後,過幾秒又生成一個uuid,則第一個部分不同,其餘相同。
(2)時鐘序列
(3)全局唯一的ieee機器識别号,如果有網卡,從網卡mac位址獲得,沒有網卡以其他方式獲得。
很友善的,直接調用uuid的randomuuid方法,即可獲得uuid對象,然後就擷取了這個唯一辨別碼。
1
2
3
4
5
<code>public static void main(string[] args)</code>
<code>{</code>
<code> </code><code>uuid uuid = uuid.randomuuid();</code>
<code> </code><code>system.out.println(uuid);</code>
<code>}</code>
run一下,可以從控制台發現:
<code><</code><code>font</code> <code>size</code><code>=</code><code>"4"</code><code>> 65752c66-bd3f-4564-b8d6-92d66796e007</</code><code>font</code><code>></code>
這就是唯一标志碼。但顯得冗長,不夠友好。如果在url後面做參數,更加不夠友好。還有存儲一個uuid要花費更多的空間。擷取的時間倒不必考慮太多。
仿着網上大牛代碼,直接上代碼:
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<code><</code><code>font</code> <code>size</code><code>=</code><code>"4"</code><code>>public static string[] chars = new string[]</code>
<code> </code><code>{</code>
<code> </code><code>"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",</code>
<code> </code><code>"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",</code>
<code> </code><code>"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v","w", "x", "y", "z"</code>
<code> </code><code>}; </code>
<code> </code><code>public static string getshortuuid()</code>
<code> </code><code>{ </code>
<code> </code><code>stringbuffer stringbuffer = new stringbuffer(); </code>
<code> </code><code>string uuid = uuid.randomuuid().tostring().replace("-", ""); </code>
<code> </code><code>for (int i = 0; i < </code><code>8</code><code>; i++)</code>
<code> </code><code>{ </code>
<code> </code><code>string </code><code>str</code> <code>= </code><code>uuid</code><code>.substring(i * 4, i * 4 + 4); </code>
<code> </code><code>int </code><code>strinteger</code> <code>= integer.parseint(str, 16); </code>
<code> </code><code>stringbuffer.append(chars[strinteger % 0x3e]); </code>
<code> </code><code>} </code>
<code> </code>
<code> </code><code>return stringbuffer.tostring(); </code>
<code> </code><code>} </font></code>
用300個測試下,沒問題。足夠用了,能适應環境場景即可。