短网址服务两种不同算法JAVA实现
- - Java - 编程语言 - ITeye博客 短网址(Short URL) ,顾名思义就是看起来很短的网址. 自从twitter推出短网址服务以后,各大互联网公司都推出了自己的短网. 个人感觉短网址最大的优点就是短,字符少,便于发布、传播、复制和存储. 通过网上的搜索,感觉流传了2种短网址算法,一种是基于MD5码的,一种是基于自增序列的.
static final char[] DIGITS = { '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', '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' };
public String shorten(String longUrl, int urlLength) { if (urlLength < 0 || urlLength > 6) { throw new IllegalArgumentException("the length of url must be between 0 and 6"); } String md5Hex = DigestUtils.md5Hex(longUrl); // 6 digit binary can indicate 62 letter & number from 0-9a-zA-Z int binaryLength = urlLength * 6; long binaryLengthFixer = Long.valueOf(StringUtils.repeat("1", binaryLength), BINARY); for (int i = 0; i < 4; i++) { String subString = StringUtils.substring(md5Hex, i * 8, (i + 1) * 8); subString = Long.toBinaryString(Long.valueOf(subString, 16) & binaryLengthFixer); subString = StringUtils.leftPad(subString, binaryLength, "0"); StringBuilder sbBuilder = new StringBuilder(); for (int j = 0; j < urlLength; j++) { String subString2 = StringUtils.substring(subString, j * 6, (j + 1) * 6); int charIndex = Integer.valueOf(subString2, BINARY) & NUMBER_61; sbBuilder.append(DIGITS[charIndex]); } String shortUrl = sbBuilder.toString(); if (lookupLong(shortUrl) != null) { continue; } else { return shortUrl; } } // if all 4 possibilities are already exists return null; }
private AtomicLong sequence = new AtomicLong(0); @Override protected String shorten(String longUrl) { long myseq = sequence.incrementAndGet(); String shortUrl = to62RadixString(myseq); return shortUrl; } private String to62RadixString(long seq) { StringBuilder sBuilder = new StringBuilder(); while (true) { int remainder = (int) (seq % 62); sBuilder.append(DIGITS[remainder]); seq = seq / 62; if (seq == 0) { break; } } return sBuilder.toString(); }