核心原理
- 長網址 → MD5 → 查快取是否存在
- 不存在則原子遞增 ID → Base62 編碼為短碼
- 雙向映射:`md5 -> id`、`shortCode -> 長網址`
- 返回 `https://short.domain/{shortCode}`
完整實現
<?php
class ShortUrlService
{
private \Memcached $mem;
private string $baseUrl;
public function __construct(array $memServers, string $baseUrl = 'https://s.example.com/')
{
$this->mem = new \Memcached();
$this->mem->addServers($memServers);
$this->baseUrl = rtrim($baseUrl, '/') . '/';
}
public function encode(string $longUrl): ?string
{
$longUrl = trim($longUrl);
if (!preg_match('~^https?://~i', $longUrl)) return null;
$md5 = md5($longUrl);
$id = $this->mem->get($md5);
if ($id === false) {
// 原子遞增獲取唯一 ID
$id = $this->mem->increment('short_url_seq');
if ($id === false) {
$this->mem->set('short_url_seq', 10000);
$id = $this->mem->increment('short_url_seq');
}
// 雙向寫入
$this->mem->set($md5, $id);
$code = $this->intToBase62($id);
$this->mem->set($code, $longUrl);
} else {
$code = $this->intToBase62($id);
}
return $this->baseUrl . $code;
}
public function decode(string $shortUrl): ?string
{
$code = str_replace($this->baseUrl, '', trim($shortUrl));
return $this->mem->get($code);
}
private function intToBase62(int $num, int $base = 62): string
{
$index = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
if ($num === 0) return '0';
$out = '';
while ($num > 0) {
$out = $index[$num % $base] . $out;
$num = (int)($num / $base);
}
return $out;
}
}
// 使用示範
$svc = new ShortUrlService([
['127.0.0.1', 11211],
]);
$long = 'https://www.example.com/very/long/url/with/query?foo=bar';
$short = $svc->encode($long);
echo "Short: $short\n";
echo "Original: " . $svc->decode($short) . "\n";
?>
關鍵設計細節
- Base62 編碼:0-9a-zA-Z,長度極短(1000萬約 4 碼),URL 安全
- Memcached 原子操作:`increment` 保證 ID 唯一,無鎖競爭
- 去重:MD5 作為長網址指紋,避免重複生成
- 過期策略:可對 `shortCode` 設置 TTL,或定期掃描清理
生產環境增強
- 持久化備份:定期同步至 MySQL/Redis Cluster
- 高可用:Memcached 叢集 + 一致性哈希
- 統計追蹤:點擊計數、Referrer、地理位置
- 防濫用:API 限流、驗證碼、域名白名單
- 自定義短碼:允許用戶指定 `code`,需檢查衝突