先看下 Nicholas C. Zakas 的這篇文章How CDNs work。
接下來的內容大部分是對這篇文章的摘抄。
什么是 CDNs ?
Content Delivery Networks,即內容分發網絡。怎么理解呢?下面引用 NCZ 的一段描述:
Physics determines how fast one computer can contact another over physical connections, and so attempting to access a server in China from a computer in the United States will take longer than trying to access a U.S. server from within the U.S. To improve user experience and lower transmission costs, large companies set up servers with copies of data in strategic geographic locations around the world. This is called a CDN, and these servers are called edge servers, as they are closest on the company’s network to the end-user.
簡而言之,CDNs 就是一些(緩存)服務器。設立在用戶端與源服務器之間,用來存放符合緩存規則(HTTP headers設置)的數據副本。
為什么要用 CDNs ?
The goal of a CDNs is to serve content to end-users with high availability and high performance.
DNS 解析
什么是 DNS
當用戶代理(瀏覽器)發起一個域名請求,DNS服務器會對請求進行解析查詢并返回相應的IP地址。如果該域名請求由CDNs負責處理則返回相應CDN域名地址。
CDNs 內部 DNS 解析
When a user makes a request to a CDN hostname, DNS will resolve to an optimized server (based on location, availability, cost, and other metrics) and that server will handle the request.
當用戶代理(瀏覽器)發起一個域名由CDN負責處理的DNS域名請求后,處理該DNS域名請求的CDN服務器會根據DNS解析器的IP地址做地理位置的查詢,然后返回一個距離那個地理位置最近的一個CDN服務器的IP。
訪問內容
端服務器是跟瀏覽器緩存工作方式類似的緩存代理。當一個請求來到端服務器,服務器首先檢查緩存看一下請求的內容是不是存在。緩存的key是整個包括查詢字符串的URL(正如在瀏覽器中一樣)。如果內容在緩存中,并且緩存條目沒有過期,那么這份內容就直接從端服務器中提供出去。可如果,內容不在緩存里或者緩存條目已經過期,那么端服務器發一個請求到原始服務器去獲取信息。原始服務器是內容的真相的源頭并且能提供所有在CDN上有的內容。當端服務器從原始服務器收到響應,它把根據http響應頭把內容存儲在緩存里。