短 URL 服務(wù),怎么設(shè)計(jì)與實(shí)現(xiàn)?
閱讀本文大概需要 5 分鐘。
前言

短. 短信和許多平臺(tái)(微博)有字?jǐn)?shù)限制,太長的鏈接加進(jìn)去都沒有辦法寫正文了.
好看. 比起一大堆不知所以的參數(shù),短鏈接更加簡潔友好.
方便做一些統(tǒng)計(jì).你點(diǎn)了鏈接會(huì)有人記錄然后分析的.
安全. 不暴露訪問參數(shù).
短URL基礎(chǔ)原理
有一個(gè)服務(wù),將要發(fā)送給你的長URL對(duì)應(yīng)到一個(gè)短URL上.例如
www.baidu.com -> www.t.cn/1把短url拼接到短信等的內(nèi)容上發(fā)送.
用戶點(diǎn)擊短URL,瀏覽器用301/302進(jìn)行重定向,訪問到對(duì)應(yīng)的長URL.
展示對(duì)應(yīng)的內(nèi)容.
服務(wù)設(shè)計(jì)
對(duì)應(yīng)關(guān)系如何存儲(chǔ)?
如何保證長短鏈接一一對(duì)應(yīng)?
短URL的存儲(chǔ)
高并發(fā)
分布式
實(shí)現(xiàn)
package util;
import redis.clients.jedis.Jedis;
/**
* Created by pfliu on 2019/06/23.
*/
publicclass ShortUrlUtil {
privatestaticfinal String SHORT_URL_KEY = "SHORT_URL_KEY";
privatestaticfinal String LOCALHOST = "http://localhost:4444/";
privatestaticfinal String SHORT_LONG_PREFIX = "short_long_prefix_";
privatestaticfinal String CACHE_KEY_PREFIX = "cache_key_prefix_";
privatestaticfinalint CACHE_SECONDS = 1 * 60 * 60;
privatefinal String redisConfig;
privatefinal Jedis jedis;
public ShortUrlUtil(String redisConfig) {
this.redisConfig = redisConfig;
this.jedis = new Jedis(this.redisConfig);
}
public String getShortUrl(String longUrl, Decimal decimal) {
// 查詢緩存
String cache = jedis.get(CACHE_KEY_PREFIX + longUrl);
if (cache != null) {
return LOCALHOST + toOtherBaseString(Long.valueOf(cache), decimal.x);
}
// 自增
long num = jedis.incr(SHORT_URL_KEY);
// 在數(shù)據(jù)庫中保存短-長URL的映射關(guān)系,可以保存在MySQL中
jedis.set(SHORT_LONG_PREFIX + num, longUrl);
// 寫入緩存
jedis.setex(CACHE_KEY_PREFIX + longUrl, CACHE_SECONDS, String.valueOf(num));
return LOCALHOST + toOtherBaseString(num, decimal.x);
}
/**
* 在進(jìn)制表示中的字符集合
*/
finalstaticchar[] 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'};
/**
* 由10進(jìn)制的數(shù)字轉(zhuǎn)換到其他進(jìn)制
*/
private String toOtherBaseString(long n, int base) {
long num = 0;
if (n < 0) {
num = ((long) 2 * 0x7fffffff) + n + 2;
} else {
num = n;
}
char[] buf = newchar[32];
int charPos = 32;
while ((num / base) > 0) {
buf[--charPos] = digits[(int) (num % base)];
num /= base;
}
buf[--charPos] = digits[(int) (num % base)];
returnnew String(buf, charPos, (32 - charPos));
}
enum Decimal {
D32(32),
D64(64);
int x;
Decimal(int x) {
this.x = x;
}
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println(new ShortUrlUtil("localhost").getShortUrl("www.baidudu.com", Decimal.D32));
System.out.println(new ShortUrlUtil("localhost").getShortUrl("www.baidu.com", Decimal.D64));
}
}
}
推薦閱讀:
微信掃描二維碼,關(guān)注我的公眾號(hào)
朕已閱?
評(píng)論
圖片
表情

