生成思路:
1.將"原始鏈接(長鏈接)+key(自定義字符串,防止算法泄漏)"MD5加密
2.把加密字符按照 8 位一組 16 進制與 0x3FFFFFFF 進行位與運算,把得到的值與 0x0000003D 進行位與運算,取得字符數組 chars 索引,把取得的字符相加,每次循環按位右移 5 位,把字符串存入對應索引的輸出數組(4組6位字符串)
3.生成4以下的隨機數,從輸入數組中取出隨機數對應位置的字符串,作為短鏈,存入數據庫或者NoSql
解析方式
編寫一個web處理程序,把從ur(如:http://url.51bi.com/zAnuAn)中解析短鏈接,將解析到的短鏈接(zAnuAn)與數據庫中存入的原始鏈接進行匹配,跳轉到匹配到的原始鏈接
package com.bjdata.test;
import java.security.MessageDigest;
import java.util.Random;
public class ShortUrlTest {
public static void main(String[] args) {
String sLongUrl = "http://www.51bi.com/bbs/_t_278433840/"; // 原始鏈接
System.out.println("長鏈接:"+sLongUrl);
String[] aResult = shortUrl(sLongUrl);//將產生4組6位字符串
// 打印出結果
for (int i = 0; i < aResult.length; i++) {
System.out.println("[" + i + "]:" + aResult[i]);
}
Random random=new Random();
int j=random.nextInt(4);//產成4以內隨機數
System.out.println("短鏈接:"+aResult[j]);//隨機取一個作為短鏈
}
public static String[] shortUrl(String url) {
// 可以自定義生成 MD5 加密字符傳前的混合 KEY
String key = "test";
// 要使用生成 URL 的字符
String[] chars = new String[] { "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", "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "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"
};
// 對傳入網址進行 MD5 加密
String hex = md5ByHex(key + url);
String[] resUrl = new String[4];
for (int i = 0; i < 4; i++) {
// 把加密字符按照 8 位一組 16 進制與 0x3FFFFFFF 進行位與運算
String sTempSubString = hex.substring(i * 8, i * 8 + 8);
// 這里需要使用 long 型來轉換,因為 Inteper .parseInt() 只能處理 31 位 , 首位為符號位 , 如果不用long ,則會越界
long lHexLong = 0x3FFFFFFF & Long.parseLong(sTempSubString, 16);
String outChars = "";
for (int j = 0; j < 6; j++) {
// 把得到的值與 0x0000003D 進行位與運算,取得字符數組 chars 索引
long index = 0x0000003D & lHexLong;
// 把取得的字符相加
outChars += chars[(int) index];
// 每次循環按位右移 5 位
lHexLong = lHexLong >> 5;
}
// 把字符串存入對應索引的輸出數組
resUrl[i] = outChars;
}
return resUrl;
}
/**
* MD5加密(32位大寫)
* @param src
* @return
*/
public static String md5ByHex(String src) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] b = src.getBytes();
md.reset();
md.update(b);
byte[] hash = md.digest();
String hs = "";
String stmp = "";
for (int i = 0; i < hash.length; i++) {
stmp = Integer.toHexString(hash[i] & 0xFF);
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
} catch (Exception e) {
return "";
}
}
}
運行結果
長鏈接:http://www.51bi.com/bbs/_t_278433840/ [0]:fa6bUr [1]:ryEfeq [2]:zAnuAn [3]:auIJne 短鏈接:zAnuAn
轉:https://www.cnblogs.com/zhanghaoh/archive/2012/12/24/2831264.html

