導航:首頁 > 編程語言 > javauuid字元串

javauuid字元串

發布時間:2023-12-10 20:39:36

java生成唯一標識符有什麼用

有時我們不依賴於資料庫中自動遞增的欄位產生唯一ID,比如多表同一欄位需要統一一個唯一ID,這時就需要用程序來生成一個唯一的全局ID,然後在資料庫事務中同時插入到多章表中實現同步.
在java中有個類工具很好的實現產生唯一ID(UUID),但是由數字和字母及中劃線組成的,故資料庫欄位應該設置為char 並相應的建立索引.
UUID是128位整數(16位元組)的全局唯一標識符(Universally Unique Identifier).
指在一台機器上生成的數字,它保證對在同一時空中的所有機器都是唯一的.通常平台會提供生成UUID的API.UUID按照開放軟體基金會(OSF)制定的標准計算,用到了乙太網卡地址,納秒級時間,晶元ID碼和許多可能的數字.由以下幾部分的組合:當前日期和時間(UUID的第一個部分與時間有關,如果你在生成一個 UUID之後,過幾秒又生成一個UUID,則第一個部分不同,其餘相同),時鍾序列,全局唯一的IEEE機器識別號(如果有網卡,從網卡獲得,沒有網卡以其他方式獲得),UUID的唯一缺陷在於生成的結果串會比較長.關於UUID這個標准使用最普遍的是微軟的GUID(Globals Unique Identifiers).
在ColdFusion中可以用CreateUUID()函數很簡單的生成UUID,其格式為:xxxxxxxx- xxxx-xxxx-xxxxxxxxxxxxxxxx(8-4-4-16),其中每個 x 是 0-9 或 a-f 范圍內的一個十六進制的數字.而標準的UUID格式為:xxxxxxxx-xxxx-xxxx-xxxxxx-xxxxxxxxxx (8-4-4-4-12)
,可以從cflib 下載CreateGUID() UDF進行轉換.
使用UUID的好處在分布式的軟體系統中(比如:DCE/RPC, COM+,CORBA)就能體現出來,它能保證每個節點所生成的標識都不會重復,並且隨著WEB服務等整合技術的發展,UUID的優勢將更加明顯.
關於UUID的更多信息可以多google 一下.
Java生成UUID
UUID(Universally Unique Identifier)全局唯一標識符,是指在一台機器上生成的數字,它保證對在同一時空中的所有機器都是唯一的.按照開放軟體基金會(OSF)制定的標准計算,用到了乙太網卡地址,納秒級時間,晶元ID碼和許多可能的數字.由以下幾部分的組合:當前日期和時間(UUID的第一個部分與時間有關,如果你在生成一個UUID之後,過幾秒又生成一個UUID,則第一個部分不同,其餘相同),時鍾序列,全局唯一的IEEE機器識別號(如果有網卡,從網卡獲得,沒有網卡以其他方式獲得),UUID的唯一缺陷在於生成的結果串會比較長.
在Java中生成UUID主要有以下幾種方式:
JDK1.5
如果使用的JDK1.5的話,那麼生成UUID變成了一件簡單的事,以為JDK實現了UUID:
java.util.UUID, 直接調用即可.
UUID uuid = UUID.randomUUID();
String s = UUID.randomUUID().toString();//用來生成資料庫的主鍵id非常不錯..
Java代碼
package com.taobao.tddl.client.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;

/**
* @author huangshang
*
*/
public class UniqId {
private static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

private static Map<Character, Integer> rDigits = new HashMap<Character, Integer>(
16);
static {
for (int i = 0; i < digits.length; ++i) {
rDigits.put(digits[i], i);
}
}

private static UniqId me = new UniqId();
private String hostAddr;
private Random random = new SecureRandom();
private MessageDigest mHasher;
private UniqTimer timer = new UniqTimer();

private ReentrantLock opLock = new ReentrantLock();

private UniqId() {
try {
InetAddress addr = InetAddress.getLocalHost();

hostAddr = addr.getHostAddress();
} catch (IOException e) {
hostAddr = String.valueOf(System.currentTimeMillis());
}

if (hostAddr == null || hostAddr.length() == 0
|| "127.0.0.1".equals(hostAddr)) {
hostAddr = String.valueOf(System.currentTimeMillis());
}

try {
mHasher = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException nex) {
mHasher = null;
}
}

/**
* 獲取UniqID實例
*
* @return UniqId
*/
public static UniqId getInstance() {
return me;
}

/**
* 獲得不會重復的毫秒數
*
* @return
*/
public long getUniqTime() {
return timer.getCurrentTime();
}

/**
* 獲得UniqId
*
* @return uniqTime-randomNum-hostAddr-threadId
*/
public String getUniqID() {
StringBuffer sb = new StringBuffer();
long t = timer.getCurrentTime();

sb.append(t);

sb.append("-");

sb.append(random.nextInt(8999) + 1000);

sb.append("-");
sb.append(hostAddr);

sb.append("-");
sb.append(Thread.currentThread().hashCode());

return sb.toString();
}

/**
* 獲取MD5之後的uniqId string
*
* @return uniqId md5 string
*/
public String getUniqIDHashString() {
return hashString(getUniqID());
}

/**
* 獲取MD5之後的uniqId
*
* @return byte[16]
*/
public byte[] getUniqIDHash() {
return hash(getUniqID());
}

/**
* 對字元串進行md5
*
* @param str
* @return md5 byte[16]
*/
public byte[] hash(String str) {
opLock.lock();
try {
byte[] bt = mHasher.digest(str.getBytes("UTF-8"));
if (null == bt || bt.length != 16) {
throw new IllegalArgumentException("md5 need");
}
return bt;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("unsupported utf-8 encoding", e);
} finally {
opLock.unlock();
}
}

/**
* 對二進制數據進行md5
*
* @param str
* @return md5 byte[16]
*/
public byte[] hash(byte[] data) {
opLock.lock();
try {
byte[] bt = mHasher.digest(data);
if (null == bt || bt.length != 16) {
throw new IllegalArgumentException("md5 need");
}
return bt;
} finally {
opLock.unlock();
}
}

/**
* 對字元串進行md5 string
*
* @param str
* @return md5 string
*/
public String hashString(String str) {
byte[] bt = hash(str);
return bytes2string(bt);
}

/**
* 對位元組流進行md5 string
*
* @param str
* @return md5 string
*/
public String hashBytes(byte[] str) {
byte[] bt = hash(str);
return bytes2string(bt);
}

/**
* 將一個位元組數組轉化為可見的字元串
*
* @param bt
* @return
*/
public String bytes2string(byte[] bt) {
int l = bt.length;

char[] out = new char[l << 1];

for (int i = 0, j = 0; i < l; i++) {
out[j++] = digits[(0xF0 & bt[i]) >>> 4];
out[j++] = digits[0x0F & bt[i]];
}

return new String(out);
}

/**
* 將字元串轉換為bytes
*
* @param str
* @return byte[]
*/
public byte[] string2bytes(String str) {
if (null == str) {
throw new NullPointerException("參數不能為空");
}
if (str.length() != 32) {
throw new IllegalArgumentException("字元串長度必須是32");
}
byte[] data = new byte[16];
char[] chs = str.toCharArray();
for (int i = 0; i < 16; ++i) {
int h = rDigits.get(chs[i * 2]).intValue();
int l = rDigits.get(chs[i * 2 + 1]).intValue();
data[i] = (byte) ((h & 0x0F) << 4 | (l & 0x0F));
}
return data;
}

/**
* 實現不重復的時間
*
* @author dogun
*/
private static class UniqTimer {
private AtomicLong lastTime = new AtomicLong(System.currentTimeMillis());

public long getCurrentTime() {
return this.lastTime.incrementAndGet();
}
}
}

㈡ java 登陸時的驗證碼怎麼做

後台寫一個生成圖片隨機的代碼,生成圖片給前台。切換圖片的時候,使用ajax獲取圖片數據就行。
附上生成圖片的代碼
public class ValidateCode {

private int width=180;
private int height=60;
private int codeCount = 4;
private int x = 0;
private int codeY;
private String Code;
private BufferedImage buffImg;
static char[] codeSequence = { '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','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', 'o', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
private int fontHeight;

public ValidateCode() {
x = width / (codeCount + 2);
fontHeight = height - 2;
codeY = height - 4;
CreateCode();
}

public void CreateCode(){

// 定義圖像buffer
BufferedImage buffImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
// 創建一個隨機數生成器類
Random random = new Random();

// 將圖像填充為白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);

// 創建字體,字體的大小應該根據圖片的高度來定。
Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
// 設置字體。
g.setFont(font);

// 畫邊框。
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);

// randomCode用於保存隨機產生的驗證碼,以便用戶登錄後進行驗證。
StringBuffer randomCode = new StringBuffer();
int red = 0, green = 0, blue = 0;

// 隨機產生codeCount數字的驗證碼。
for (int i = 0; i < codeCount; i++) {
// 得到隨機產生的驗證碼數字。
String strRand = String.valueOf(codeSequence[random.nextInt(62)]);
// 產生隨機的顏色分量來構造顏色值,這樣輸出的每位數字的顏色值都將不同。
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);

// 用隨機產生的顏色將驗證碼繪制到圖像中。
g.setColor(new Color(red, green, blue));
g.drawString(strRand, (i ) * x+20, codeY);

// 將產生的四個隨機數組合在一起。
randomCode.append(strRand);
}
this.Code=randomCode.toString().toUpperCase();
this.buffImg=buffImg;

}

public String getCode() {
return Code;
}

public void setCode(String code) {
Code = code;
}

public BufferedImage getBuffImg() {
return buffImg;
}

public void setBuffImg(BufferedImage buffImg) {
this.buffImg = buffImg;
}
}

㈢ 用Java 生成一個長度為40的、完全由16進制數組成的隨機字元串的方法:

用java.util.UUID 可以實現這個。
下面是樣例 :
ss[0]=====4cdbc040-657a-4847-b266-7e31d9e2c3d9,
ss[1]=====72297c88-4260-4c05-9b05-d28bfb11d10b,
ss[2]=====6d513b6a-69bd-4f79-b94c-d65fc841ea95,
ss[3]=====d897a7d3-87a3-4e38-9e0b-71013a6dbe4c,

閱讀全文

與javauuid字元串相關的資料

熱點內容
matlab實用教程pdf 瀏覽:769
伺服器加密方式哪種好 瀏覽:121
顯示加密服務超時 瀏覽:611
日語口譯pdf 瀏覽:433
外人如何評價身邊的程序員 瀏覽:105
霍夫曼編碼壓縮演算法 瀏覽:122
我想學習單片機 瀏覽:644
陳寶蓮拍過 瀏覽:336
遙調命令的設定命令實現過程 瀏覽:76
演算法中最壞情況都為多少 瀏覽:995
排序演算法圖形化展示 瀏覽:782
看電影免費網站入口 瀏覽:447
加密U盤啟動區和交換區格式化 瀏覽:247
求不需要下載播放器就能看的網站 瀏覽:828
日本重生電影在線 瀏覽:623
女的被一個小孩上了 瀏覽:948
macandroid找不到設備 瀏覽:514
漫威電影不能投屏了怎麼破 瀏覽:308
安卓qq最新版本怎麼解綁手機號 瀏覽:681
經典三極3d版古裝劇 瀏覽:172