短 URL 服務(wù)的設(shè)計(jì)以及實(shí)現(xiàn)

- 背景 -


- 端 URL 的好處 -
短信和許多平臺(tái)(微博)有字?jǐn)?shù)限制 ,太長(zhǎng)的鏈接加進(jìn)去都沒(méi)有辦法寫正文了。 好看。 比起一大堆不知所以的參數(shù),短鏈接更加簡(jiǎn)潔友好。 方便做一些統(tǒng)計(jì)。 你點(diǎn)了鏈接會(huì)有人記錄然后分析的。 安全。 不暴露訪問(wèn)參數(shù)。

- 短 URL 基礎(chǔ)原理 -
有一個(gè)服務(wù),將要發(fā)送給你的長(zhǎng)URL對(duì)應(yīng)到一個(gè)短URL上.例如www.baidu.com -> www.t.cn/1。 把短URL拼接到短信等的內(nèi)容上發(fā)送。. 用戶點(diǎn)擊短URL,瀏覽器用301/302進(jìn)行重定向,訪問(wèn)到對(duì)應(yīng)的長(zhǎng)URL。 展示對(duì)應(yīng)的內(nèi)容。

- 服務(wù)設(shè)計(jì) -
對(duì)應(yīng)關(guān)系如何存儲(chǔ)?
如何保證長(zhǎng)短鏈接一一對(duì)應(yīng)?
短URL的存儲(chǔ)
高并發(fā)
緩存
批量發(fā)號(hào)
分布式
實(shí)現(xiàn)
package util;
import redis.clients.jedis.Jedis;
/**
* Created by pfliu on 2019/06/23.
*/
public class ShortURLUtil {
private static final String SHORT_URL_KEY = "SHORT_URL_KEY";
private static final String LOCALHOST = "http://localhost:4444/";
private static final String SHORT_LONG_PREFIX = "short_long_prefix_";
private static final String CACHE_KEY_PREFIX = "cache_key_prefix_";
private static final int CACHE_SECONDS = 1 * 60 * 60;
private final String redisConfig;
private final 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ù)庫(kù)中保存短-長(zhǎng)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)制表示中的字符集合
*/
final static 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'};
/**
* 由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 = new char[32];
int charPos = 32;
while ((num / base) > 0) {
buf[--charPos] = digits[(int) (num % base)];
num /= base;
}
buf[--charPos] = digits[(int) (num % base)];
return new 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));
}
}
}作者:翁智華
來(lái)源:
https://www.cnblogs.com/wzh2010/p/14454954.html

評(píng)論
圖片
表情
